Turn off a prototype object

I am trying to understand how prototypes work. Why the next 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? :( 
+4
source share
1 answer

I think you mean in the last line aa.hi instead of aa.hello .

It gives you undefined because A.prototype is assigned after the new object ( aa ) has already been created.

In the second line:

 //... aa = new A; //... 

This will create an object that inherits from A.prototype , currently A.prototype is a simple empty object that inherits from Object.prototype .

This object will still refer to the internal [[Prototype]] property of the aa object instance.

Changing A.prototype after this will not change the direct inheritance relationship between aa and this object.

There is actually no standard way to change the internal [[Prototype]] 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" 
+12
source

Source: https://habr.com/ru/post/1333825/


All Articles