最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Switching out an object's prototype - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 12

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"
发布评论

评论列表(0)

  1. 暂无评论