Monday, August 26, 2013

object.__proto__ and the prototype , Javascript

Everything in javascript is object.
And every object, it may be a function/ {} / new Object() , in javascript has an internal property called [[proto]].

[[proto]] is the very reason for prototype inheritance in javascript.

This internal property is exposed to the programmer through proto. This is a non standard.
Not all JS environments support this.

How does an object we create using constructor functions gets its [[proto]]?

Only objects whose [[class]] is "Function" gets the property 'prototype'. What it means is that every function declared when executed by the JS engine, it creates an object. Its [[class]] is set to "Function" and a property "prototype" is attached to this function object. By default this prototype is an object with one property "constructor" pointing to the function object.

When the above function is invoked as part of new operator like new constructorFn() , the JS engine creates an object , its [[class]] property set to "Object" and [[proto]] property set to the object pointed to by the [[proto]] of the constructor function.

Since this new created object is of class "Object" , it does not have the "prototype" property.
But has __proto__ pointing to the object as explained above

In nutshell, proto exists is in every object.

Prototype exists, by default, only in objects whose [[class]] is 'Function'.What this means is only functions (created via function statement , function expression , Function constructor fn) will have this property.

No comments:

Post a Comment