0

我在 setInterval 中调用方法时遇到问题...这是我的代码片段...

var example = function(){

    this.animate = function(){
        console.log("Animate.");
    }

    this.updateTimer = function(){ // This is being called...
        this.timer = setInterval(function(){
            this.animate(); // A "Undefined Is Not A Function" error is being thrown here.
        }, 1);
    }

}
4

2 回答 2

2

使用 BIND(正如@torazaburo 所说)

也许是最佳实践

http://jsfiddle.net/rnrlabs/Lnmex1y7/

var example = function(){
    this.animate = function(){
        console.log("Animate.");
    }    
    this.updateTimer = function() { // This is being called...
        this.timer = setInterval(this.animate.bind(this), 1);
    }
}

或者..使用闭包

http://jsfiddle.net/rnrlabs/zk6hdnf2/

var example = function(){

    var self = this; // this creates a closure

    this.animate = function(){
        console.log("Animate.");
    }

    this.updateTimer = function(){ 
        this.timer = setInterval(function(){
            // 'this' here means window element.
            self.animate(); 
        }, 1);
    }

}
于 2014-09-06T06:45:33.443 回答
0

您不能this在 setInterval 中使用此代码

编辑this.animate()example.animate()

使用此代码

var example = function(){

    this.animate = function(){
        console.log("Animate.");
    }

    this.updateTimer = function(){ // This is being called...
        this.timer = setInterval(function(){
            example.animate(); // A "Undefined Is Not A Function" error is being thrown here.
        }, 1);
    }

}
于 2014-09-06T07:42:39.007 回答