簡體   English   中英

ECMAScript 6-如何在類中傳遞對“自我”的引用?

[英]ECMAScript 6 - How do I pass a reference to “self” from within a class?

我該如何完成以下操作(因為通過操作無法達到預期的結果)。 引用行“ this.AddComponent(new MoveComponent(0,0,this));” 在“平方”類中:

// 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;
     }
}

更改為Shape類中的AddComponent方法的實現:

 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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM