关于"这个"的javaScript问题

时间:2017-06-07 08:55:09

标签: javascript

我试图建立一个游戏恶魔,当我尝试将clickEventHanlder添加到按钮时遇到问题,代码就在这里:

function GameConstructor(){
    this.start = startGame;
    this.count = 5;
    ...
    function startGame(){
        if(this.count > 5){ //here goes the problem, this don't point to the game object when I click the button
            ...
        }
}
...
var game = new GameConstructor(); //game object has a method called start
$("#someBtn").click(game.start); //in the method start this now point to the button so this.count is undefined.

我知道我可以定义一个全局变量count = 5来解决这个问题,但我只是想知道是否有办法以我原来的方式修复?感谢。

2 个答案:

答案 0 :(得分:1)

我不是一个完整的JavaScript向导,但我的猜测是嵌套函数中的this指的是嵌套函数,而不是外部实例。

许多人选择创建一个self变量,以便对此范围内容更加明确。也许试试这个:

function GameConstructor(){
    var self = this;    // <-- here, then reference self subsequently
    self.start = startGame;
    self.count = 5;
    ...
    function startGame(){
        if(self.count > 5){ //here goes the problem, this don't point to the game object when I click the button
            ...
        }
}

答案 1 :(得分:0)

这始终指向Javascript中的当前函数上下文。意味着'this'之外的最低功能。所以,你可以这样做;

function GameConstructor(){
    var self= this;
    this.start = startGame;
    this.count = 5;
    ...
    function startGame(){
        if(self.count > 5){ //here goes the problem, this don't point to the game object when I click the button
            ...
        }
}
...
var game = new GameConstructor(); //game object has a method called start
$("#someBtn").click(game.start); //in the method start this now point to the button so this.count is undefined.