0

我已经声明了一个带有变量和方法的对象。这里简化了

var myObj = {
    myTimer: null,
    startTimer: function(){
        clearTimeout(myObj.myTimer);
        myObj.myTimer = setTimeout("myObj.myFunction()", 250);
    },
    myFunction: function(){
        alert('Hi');
    }
};

调用 startTimer 后,控制台会打印以下错误

Uncaught ReferenceError: myFunction is not defined
Uncaught ReferenceError: startTimer is not defined

我该如何解决这个问题?

4

2 回答 2

2

您应该将函数传递给setTimeout而不是字符串,最好使用this而不是对象名称:

var myObj = {
    myTimer: null,
    startTimer: function(){
        clearTimeout(this.myTimer);
        this.myTimer = setTimeout(this.myFunction, 2500);
    },
    myFunction: function(){
        alert('Hi');
    }
};

这是工作小提琴:http: //jsfiddle.net/vyshniakov/fpZBa/

于 2012-10-16T11:46:43.853 回答
0

There was actually nothing wrong with my code, although it could probably be more pretty.

The problem was how i was calling the methods, and not within the object itself.

于 2012-10-16T11:55:38.527 回答