How to use encoded javascript prototype inheritance?

function Entity() {
    this.a = {a: 4};
    this.b = 5;
}

function Thing() {}
Thing.prototype = new Entity;

var thing1 = new Thing;
thing1.a.a = 3;
thing1.b = 4;
var thing2 = new Thing;
console.log(thing2.a.a); // prints 3 instead of 4. I would like 4.
console.log(thing2.b) // prints 5 as wanted

I find it hard to set prototypal inheritance in javascript. Ideally, I want both thing1 and thing2 to have their own clean copy of the โ€œnew Entity prototypeโ€.

use this.__proto__is what i want to avoid

[edit]

I have a general idea of โ€‹โ€‹how this works.

Setting thing1.b sets property b in the Thing instance. which does not apply to Entity.b defined in the prototype chain.

If the installation of the thing1.aa object on the Thing instance cannot be completed, because this will cause a "can not set a on undefined" error. It is then that he rises up the prototype chain to find Entity.a, which is defined and sets Entity.aa to a new value.

[ ]

@IvoWetzel, thing1.b , . , thing1.a.a . thing1.a, , .a

+3
3

Entity Thing, :

function Entity() {
    this.a = {a: 4};
    this.b = 5;
}
Entity.prototype.c = 6;

function Thing() {
  Entity.apply(this, arguments); // ejecutes the assignments made in Entity
}
Thing.prototype = new Entity;

var a = new Thing;
a.a.a = 3;

var b = new Thing;
console.log(a.a.a); // 3
console.log(b.a.a); // 4

console.log(a.b);   // 5
console.log(b.b);   // 5

console.log(a.c);   // 6
console.log(b.c);   // 6
+6

CMS , thing2.b 5 thing2.a.a ?

var thing1 = new Thing;

// thing1 has no a, but the prototype has so a.a is essentially the a of Entity
thing1.a.a = 3;

// Sets b on thing1, setting does not go up the prototype chain(!)
thing1.b = 4;  

// that what thing1 looks like
Thing {proto: Entity { 
                      a: { <--- gets resolved 
                          a: 3 <-- gets set
                      }, 
                      b: 5
              },
              b: 4 <-- gets set directly
      }


var thing2 = new Thing;

// thing2.a does not exist, so we look up the prototype and find a on Entity
console.log(thing2.a.a); 

// thing2.b also does not exists, so once again we look up the prototype to find b on Entity
console.log(thing2.b);

// that what thing2 looks like
Thing {proto: Entity {
                      a: {
                          a: 3 <- gets resolved
                      },
                      b: 5 <- gets resolved
              }
      }

, JavaScript , . , .

+2

, JavaScript .

, this.a, a.a.a = 3;, . Thing , Entity , Thing , this.a .

this.a , , Thing. , this.a Thing.

0

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


All Articles