Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching out an object's prototype

Tags:

javascript

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? :(
like image 705
John Avatar asked Dec 17 '22 18:12

John


1 Answers

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"
like image 130
Christian C. Salvadó Avatar answered Jan 07 '23 09:01

Christian C. Salvadó