Prototype VS. __proto__ VS. [[Prototype]]
When creating a function, a property object called prototype is being created automatically (you didn\'t create it yourself) and is being attached to the function object (the constructor
).
Note: This new prototype object also points to, or has an internal-private link to, the native JavaScript Object.
Example:
function Foo () {
this.name = \'John Doe\';
}
// Foo has an object property called prototype.
// prototype was created automatically when we declared the function Foo.
Foo.hasOwnProperty(\'prototype\'); // true
// Now, we can assign properties to to the prototype object without declaring it first.
Foo.prototype.myName = function () {
return \'My name is \' + this.name;
}
If you will create a new object out of Foo
using the new
keyword, you basically creating (among other things) a new object that has an internal or private link to the function\'s prototype Foo
we discussed earlier:
var b = new Foo();
b.[[Prototype]] === Foo.prototype // true
The private linkage to that function\'s object called
[[Prototype]]
. Many browsers are providing us with a public linkage instead that called __proto__
!
To be more specific, __proto__
is actually a getter function that belong to the native JavaScript Object and returns the internal-private prototype linkage of whatever the this
binding is (returns the [[Prototype]]
of b
):
b.__proto__ === Foo.prototype // true
It is worth noting that starting of ECMAScript5
, you can also use the getPrototypeOf
method to get the internal private linkage:
Object.getPrototypeOf(b) === b.__proto__ // true
NOTE: this answer doesn\'t intend to cover the whole process of creating new objects or new constructors, but to help better understand what is
__proto__
, prototype
and [[Prototype]]
and how it works.