我正在尝试了解原型(prototype)的工作原理。为什么下面会中断?
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? :(
最佳答案
我想你的意思是在最后一行 aa.hi
而不是 aa.hello
。
它给你 undefined
因为 A.prototype
被赋值 after 新对象 (aa
) 有已经创建。
在你的第二行:
//...
aa = new A;
//...
这将创建一个继承自A.prototype
的对象,此时,A.prototype
是一个简单的空对象,它继承自对象。原型(prototype)
.
该对象将保持由 aa
对象实例的内部 [[Prototype]]
属性引用。
在此之后改变A.prototype
,不会改变aa
和那个对象之间的直接继承关系。
事实上,没有改变[[Prototype]]
内部属性的标准方法,一些实现允许您通过称为__proto__
的非标准属性进行访问。
要获得预期的结果,请尝试:
var A = function A () { this.a = 0 };
A.prototype = { hi:"hello" };
var aa = new A;
aa.hi; // "hello"
关于javascript - 切换对象的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565247/