admin管理员组文章数量:1394136
I'm trying 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'm trying 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? :(
Share
Improve this question
edited May 21, 2015 at 3:54
hello_there_andy
2,0822 gold badges22 silver badges52 bronze badges
asked Dec 30, 2010 at 18:35
JohnJohn
1971 silver badge8 bronze badges
2
- 1 woops, made a correction to aa.hi – John Commented Dec 30, 2010 at 18:48
- Removed salutation: "Thanks in advance!", don't do it next time – hello_there_andy Commented May 21, 2015 at 2:38
1 Answer
Reset to default 12I 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"
本文标签: javascriptSwitching out an object39s prototypeStack Overflow
版权声明:本文标题:javascript - Switching out an object's prototype - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744597538a2614867.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论