This figure again shows that every object has a prototype. Constructor function Foo also has its own
__proto__
which is Function.prototype, a
I happen to be learning prototype from You Don't Know JS: this & Object Prototypes, which is a wonderful book to understand the design underneath and clarify so many misconceptions (that's why I'm trying to avoid using inheritance and things like instanceof
).
But I have the same question as people asked here. Several answers are really helpful and enlightening. I'd also love to share my understandings.
Objects in JavaScript have an internal property, denoted in the specification as[[Prototype]]
, which is simply a reference to another object. Almost all objects are given a non-null
value for this property, at the time of their creation.
via __proto__
or Object.getPrototypeOf
var a = { name: "wendi" };
a.__proto__ === Object.prototype // true
Object.getPrototypeOf(a) === Object.prototype // true
function Foo() {};
var b = new Foo();
b.__proto__ === Foo.prototype
b.__proto__.__proto__ === Object.prototype
prototype
?prototype
is an object automatically created as a special property of a function, which is used to establish the delegation (inheritance) chain, aka prototype chain.
When we create a function a
, prototype
is automatically created as a special property on a
and saves the function code on as the constructor
on prototype
.
function Foo() {};
Foo.prototype // Object {constructor: function}
Foo.prototype.constructor === Foo // true
I'd love to consider this property as the place to store the properties (including methods) of a function object. That's also the reason why utility functions in JS are defined like Array.prototype.forEach()
, Function.prototype.bind()
, Object.prototype.toString().
Why to emphasize the property of a function?
{}.prototype // undefined;
(function(){}).prototype // Object {constructor: function}
// The example above shows object does not have the prototype property.
// But we have Object.prototype, which implies an interesting fact that
typeof Object === "function"
var obj = new Object();
So, Arary
, Function
, Object
are all functions. I should admit that this refreshes my impression on JS. I know functions are first-class citizen in JS but it seems that it is built on functions.
__proto__
and prototype
?__proto__
a reference works on every object to refer to its [[Prototype]]
property.
prototype
is an object automatically created as a special property of a function, which is used to store the properties (including methods) of a function object.
With these two, we could mentally map out the prototype chain. Like this picture illustrates:
function Foo() {}
var b = new Foo();
b.__proto__ === Foo.prototype // true
Foo.__proto__ === Function.prototype // true
Function.prototype.__proto__ === Object.prototype // true