'This' is not the same in constructor and inherited constructor

I have this simple inheritance pattern:

function Emitter() {
    this.dis1 = this;
};

function Person() {
    this.dis2 = this;
};
Person.prototype = new Emitter();
var p1 = new Person();
var p2 = new Person();

console.log(p1.dis1 === p2.dis1); //true - why?
console.log(p1.dis2 === p2.dis2); //false

Why are dis1 separate objects the same? Is there a workaround for this?

+4
source share
3 answers

A note on how newoperator works :

Foo = function(){};
Foo.prototype;

var bar = new Foo();

What happens on the last line, a new object is created that inherits from Foo.prototype, and then the code in the function Foois executed with thisthis new object. Then the line is initialized with this new object.


There are several drawbacks to your inheritance model, and you have discovered one of them. All the flaws are related to this line of code:

Person.prototype = new Emitter();

, , Person, - Emitter ( Emitter, ).

p1.dist1 dist1 . p1, , dist1, . p1.[[Prototype]], Person.prototype, dist1, Person.prototype ( Emitter, ).

p1.dist , p1 p1.

p2, p2.dist1, Emitter, p2.dist2 p2.


:

function Emitter() {
    this.dis1 = this;
};

function Person() {
    Emitter.call(this); // calls the parent constructor.
    this.dis2 = this;
};
Person.prototype = Object.create(Emitter.prototype); // you don't even use this line

var p1 = new Person();
var p2 = new Person();

p1.dist1 === p1 p1.dist2 === p1, p2.dist1 === p2 p2.dist2 === p2. , , Emitter , Person. , Emitter this.dis1 = this, this p1 p2.

, , :

  • , Emitter.prottoype, p1 p2
  • p1 instanceof Emitter .

, MDN.

+3

dis1 .

p1 p2, , , new Emitter(). , .

JavaScript , , Java. , Java ++ JavaScript: .

, Emitter Person, ( initialize, ).

:

function Emitter() {
}
Emitter.prototype.register = function(thing){
  if (!this.listeners) {
      this.listeners = []; 
  }
  this.listeners.push(thing);
}

function Person() {
}
Person.prototype = new Emitter();

, , , , , .

+2

dystroy, dis1 . dis1 Person s, .

function Emitter() {
    this.dis1 = this;
};

function Person() {
    Emitter.call(this);
    this.dis2 = this;
};
Person.prototype = Object.create(Emitter.prototype);
var p1 = new Person();
var p2 = new Person();

console.log(p1.dis1 === p2.dis1); //false
console.log(p1.dis2 === p2.dis2); //false

, Emitter Person, this . Person , () Person, () Emitter :

{
    dis1: Person,
    dis2: Person
}

Object.create . , Emitter , , , dis1, -.

+1
source

All Articles