【发布时间】:2018-08-03 15:00:03
【问题描述】:
我有这样的课
class Game {
constructor(player1, player2, gameId) {
this.Clockk = {
totalSeconds: timeForAnswer,
nowSeconds: timeForAnswer,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.nowSeconds -= 1;
if (self.nowSeconds == 0) {
here I want to call "answered" function
}
},
reset: function(){
this.nowSeconds = this.totalSeconds;
},
};
answered(player) {
console.log(player);
}
};
我想从this.Clockk 变量中调用Game 类的函数。
变量中的this 关键字是this.Clockkitself,我怎样才能获得父类本身?
【问题讨论】:
-
该代码至少有几个语法错误,您能否将其改正(除了您不知道如何进行的调用),因此我们不会猜测您想要做什么?
-
如果你有像
const myGame = new Game();这样的代码,那么像myGame.answered();这样的代码就可以了。但是在更好的结构中,时钟和游戏不会以这种方式相互耦合:游戏可以将回调传递给时钟,一旦时钟达到零,该回调就会被触发。然后游戏运行时钟而不是时钟运行部分游戏。 -
您可以使用箭头函数来保留 this 上下文,但我经常发现那里的灵活性不如您已经做过的那样 ->
var self = this;但是要使它更健壮,您可以这样做 @987654329 @,你可以为你的游戏做另一个,所以你的构造函数的第一行做var thisGame = this,现在你想引用什么this没有混淆。
标签: javascript node.js web browser