![](/img/trans.png)
[英]How do I reference the containing class from within a static method when “this” is already taken by the calling object?
[英]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.