JavaScript's prototype & __proto__
05 Dec 2014JavaScript’s Inheritance model is Prototype-based unlike other Object oriented programming languages which are class based.
In JavaScript, functions are similar to Objects, wherein we can add properties and methods.
Prototype
is the native property of a JavaScript function. The prototype property is for Function objects, when using new
operator to call a Function as constructor. When an object is created with the new
operator, its internal [[Prototype]]
property will be set to the object pointed to by the constructor function’s prototype property. Properties are assigned to a constructor’s prototype if they need to be inherited by its instances rather than directly assigned, to save memory.
__proto__
is the internal [[Prototype]]
property of an object, ie., the actual object that is used in the lookup chain to resolve the methods. All objects have this property.
Animal is a constructor function, and its prototype
property is sayHello method. The __proto__
property points to Object, because all Constructor functions and objects are inherited by JavaScript’s native Object
.
The Prototypal Inheritance in JavaScript is based on __proto__
property in a sense that each object is inheriting the contents of the object referenced by its __proto__
property.
Objects created using new Animal()
has a __proto__
property which points to the Animal.prototype
, whose __proto__
points to Object
.
The __proto__
property should not be accessed directly, instead Object.getPrototypeOf(object)
should be used.
So what is Prototype chaining
and how does it work ?
As we know, every Object in JavaScript has an internal property called prototype, which links to another object, also referred as the parent object. The prototype object has a prototype object of its own (similar to a father has a father of his own) , and so on, thereby creating a Prototype Chain.
When a property or method is requested and the object does not contain in its own scope, JavaScript will look up the prototype chain. Since that object also has its prototype field as well, it continues to look up until it either finds the requested property, or until it reaches the end of the chain. This is how JavaScript implements its Prototypal inheritance.