ECMAScript 6 - 如何从类中传递对“self”的引用?

时间:2017-01-27 16:59:58

标签: javascript oop ecmascript-6

如何完成以下操作(因为传递未达到预期效果)。引用“this.AddComponent(new MoveComponent(0,0,this))”行;“在“Square”课程中:

// shape.js
export default class Shape {
     constructor(name) {
         this.name = name;
         this.Components = [];
     }

     AddComponent(component) {
          this.Components.push(component);
     }
}

// component.js
export default class Component {
     constructor(name) {
          this.name = name;
     }
}

// square.js
import Shape from "./shape";
import MoveComponent from "./moveComponent";

export default class Square extends Shape {
     constructor() {
         super("square");
         this.AddComponent(new MoveComponent(0, 0, this));
     }
}

// moveComponent.js
import Component from "./component";

export default class MoveComponent extends Component {
     constructor(x, y, parentShape) {
          super("movement");
          this.x = x;
          this.y = y;
          this.ParentShape = parentShape;
     }
}

1 个答案:

答案 0 :(得分:0)

将类AddComponent中方法Shape的实施更改为:

 AddComponent(component) {
     this.Components.push(component);
 }

"use strict"

class Shape {
  constructor(name) {
    this.name = name;
    this.Components = [];
  }

  AddComponent(component) {
    this.Components.push(component);
    console.log(this)
  }
}

class Component {
  constructor(name) {
    this.name = name;
  }
}

class Square extends Shape {
  constructor() {
    super("square");
    this.AddComponent(new MoveComponent(0, 0, this));
  }
}

class MoveComponent extends Component {
  constructor(x, y, parentShape) {
    super("movement");
    this.x = x;
    this.y = y;
    this.ParentShape = parentShape;
  }
}

new Square() // logs passed arguments