What is the end of prototype chain in javascript -- null or Object.prototype?
What is the end of prototype chain in JavaScript ...?
Null. The only authority on the language is ECMA-262.
Are objects, which are not created from object literals, not linked to
Object.prototype
?
They may or many not be, e.g.
var x = Object.create(null)
has a [[Prototype]]
of null, whereas:
var y = {};
has a [[Prototype]]
of Object.prototype.
Say I have an object
var x = { len: 4, breadth: 5}
. Would JavaScript automatically create its prototypex.prototype
?
No. Function objects have default prototype objects. Plain objects have a default [[Prototype]]
(i.e. internal prototype property) that is Object.prototype (unless constructed as above).
And how long would the prototype chain be? Would
x.prototype
have only one prototype,Object.prototype
, making a 3 point chain?
Two values: Object.prototype and null.
How does JavaScript internally create automatic prototypes?
However it likes, the language specification does not define implementation, only behaviour.
It is like, if New York has an envelope and inside, it says Colorado, and Colorado has an envelope, and inside, it says San Francisco, and San Francisco has an envelope, and inside, it says "none". So is San Francisco end of the chain, or is "none" the end of chain? It may depend on how you look at it. But one thing is for sure: it points up and up the chain, for inheritance purpose (prototypal inheritance), until it reaches
null
, which means can't go further up. And make sure you know that, to go up and up the chain, it is__proto__
. It is notprototype
.Object.prototype
,Animal.prototype
are different fromx.__proto__
. The former are function objects (Object, Animal) having aprototype
property pointing to a prototype object. Andx.__proto__
is how the prototype chain is followed upward. To go up and up, it isx.__proto__.__proto__
and so on. See JavaScript's Pseudo Classical Inheritance diagram to understand it more.Object.prototype
refers to a prototype object. Quoted from MDN,null
"represents the intentional absence of any object value. It is one of JavaScript's primitive values." SoObject.prototype
andnull
are not the same thing.All JavaScript objects will have
obj.__proto__
referring ultimately to whatObject.prototype
refers to. If it is notobj.__proto__
, then it isobj.__proto__.__proto__
. If not, just go up, and up, and it will reach the prototype object whichObject.prototype
refers to. And at this point, when you go up one level (by adding a.__proto__
, then you getnull
. You can try it in Google Chrome's developer's tool:x = { a : 1 } > Object {a: 1} x.__proto__ === Object.prototype > true x.__proto__.__proto__ > null Object.prototype.__proto__ > null