Saturday, May 19, 2012

prototype vs __proto__ or proto Javascript

JavaScript prototype concept ,like closure, is very critical for efficient programming.
ECMA Script specification defines object type as collection of properties.

Each object has an internal property [[prototype]] which is the basis for all the prototype buzz in java script world. Internal property  means a.prototype (a is an object) is undefined.

function chandu(){

}

above declaration creates an object with the following properties

[[prototype]] ::: built in function prototype object
[[construct]]
[[call]]
[[class]] ::: Function
prototype ::: {constructor:chandu}
...

 As you can see we have two prototype properties
(i) [[prototype]] --- this is the object which is searched for when we try to access a property on any object if that property does not exist in the object.

(ii) prototype --- exists only for function objects.This is assigned to [[prototype]] property of any object created using the above function as constructor.
-this object is constructed using the express new Object() where Object is the built in constructor function.
-Object.prototype = the built in Object Prototype Object whose [[prototype]] ==null.This is where the prototype chain ends.

var a = new chandu();

-a is now an object created using chandu() as constructor function
-a's [[prototype]]  now holds the object referred to by the prototype(not the internal one) property of the chandu.
- there is no prototype own property in 'a' like what we had for chandu function object.

a.x  will first see if there is any property in 'a'.If not present it will search in the object referred by [[prototype]] property  of 'a'.


Lets see how the prototype chain looks for 'a'

p1 = a[[prototype]]
p2 = p[[prototype]]
p2 is the built in Object prototype object
p2[[prototype]]=null

Inheritance is achieved through the [[prototype]] internal property.And every ECMA object has this internal property.

No comments:

Post a Comment