[英]How can I access an instance of a class from a child instance?
I have a class named "Main", with one instance named "main".我有一个名为“Main”的 class,其中一个实例名为“main”。 The "main" instance has two properties that are instances of other classes, named "player" and "background". “main”实例有两个属性,它们是其他类的实例,名为“player”和“background”。 I want the child instances to be able to use each other, as well as the "main" instance.我希望子实例能够相互使用,以及“主”实例。 Below is my attempt, which throws an error: "main is undefined".下面是我的尝试,它引发了一个错误:“main is undefined”。
class Player {
constructor() {
}
x = 10;
y = 20;
};
class Background {
constructor() {
}
backgroundCenterX = main.player.x;
backgroundCenterY = main.player.y;
// the previous two lines throw an error
};
class Main {
constructor() {
this.background = new Background();
this.player = new Player();
}
};
var main = new Main();
I have tried a few things, including passing the "main" instance by reference to the constructors of the child instances, but I haven't been able to get it to work.我尝试了一些事情,包括通过引用子实例的构造函数来传递“主”实例,但我无法让它工作。 I think the code is throwing an error because the "Main" constructor hasn't finished running when the "main" instance is referenced.我认为代码会引发错误,因为引用“main”实例时“Main”构造函数尚未完成运行。
Is there any way to fix this?有没有什么办法解决这一问题?
You can pass the main
instance to the Constructor
of Player
and Background
.您可以将main
实例传递给Player
和Background
的Constructor
。
Then you can access it via this.main
然后你可以通过this.main
访问它
class Player {
constructor(main) {
this.main = main;
}
x = 10;
y = 20;
};
class Background {
constructor(main) {
this.main = main;
}
doSomeThing() {
const backgroundCenterX = this.main.player.x;
const backgroundCenterY = this.main.player.y;
console.log(backgroundCenterX, backgroundCenterY);
}
};
class Main {
constructor() {
this.background = new Background(this);
this.player = new Player(this);
}
doSomeThing() {
this.background.doSomeThing();
}
};
var main = new Main();
main.doSomeThing()
You can pass the main into the child constructors.您可以将 main 传递给子构造函数。 But the order matters, you have to construct and assign the player first if the background constructor is to access it on main.但是顺序很重要,如果后台构造函数要在 main 上访问它,则必须先构造和分配播放器。
class Player { constructor(main) { this.main = main; } x = 10; y = 20; }; class Background { constructor(main) { this.main = main; this.backgroundCenterX = this.main.player.x; this.backgroundCenterY = this.main.player.y; } }; class Main { constructor() { this.player = new Player(this); this.background = new Background(this); } }; var main = new Main(); console.log(main);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.