Switching out an object's prototype
I'm tryin开发者_运维知识库g to understand how prototypes work. Why does the following break?
var A = function A(){this.a = 0},
aa = new A;
A.prototype = {hi:"hello"};
aa.constructor.prototype //->{hi:"hello"} ok so far :)
aa.hi //undefined?? why? :(
I think you meant in the last line aa.hi
instead of aa.hello
.
It gives you undefined
because the A.prototype
is assigned after the new object (aa
) has been already created.
In your second line:
//...
aa = new A;
//...
This will create an object that inherits from A.prototype
, at this moment, A.prototype
is a simple empty object, that inherits from Object.prototype
.
This object will remain referenced by the internal [[Prototype]]
property of the aa
object instance.
Changing A.prototype
after this, will not change the direct inheritance relationship between aa
and that object.
In fact, there is no standard way to change the [[Prototype]]
internal property, some implementations give you access through a non-standard property called __proto__
.
To get the expected results, try:
var A = function A () { this.a = 0 };
A.prototype = { hi:"hello" };
var aa = new A;
aa.hi; // "hello"
精彩评论