I believe you are right in most cases.
Every object has a hidden [[Prototype]]
property, which is used for inheritance. Functions additionally have a public prototype
property, which is used only when the function is used as constructor: When an object is constructed using new
, the [[Prototype]]
property of the new object is set to the prototype
property of the function that was used as constructor.
E.g.
function C() {}
C.prototype = P1;
var obj = new C(); // obj.[[Prototype]] is now P1.
You can get the [[Prototype]]
property using Object.getPrototypeOf(<obj>)
. (This method is specified in ECMAScript 5. Older versions of JavaScript does not have any standard way of reading [[Prototype]]
).
You can usually get to the prototype through the constructor, e.g.:
obj.constructor.prototype == Object.getPrototypeOf(obj)
But this is not always the case, since the prototype property of the constructor function can be reassigned, but the [[Prototype]]
of an object cannot be reassigned after the object is created. So if you do:
C.prototype = P2;
then
obj.constructor.prototype != Object.getPrototypeOf(obj)
Because the prototype of C
is now P2
, but [[Prototype]]
of obj
is still P1
.
Note that it is only functions that have a prototype
property. Note also that the prototype
property of a function is not the same as the [[Prototype]]
property of the function!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…