在setInterval中调用方法时出错

时间:2014-09-06 06:43:07

标签: javascript setinterval undefined-function

我无法在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);
    }

}

2 个答案:

答案 0 :(得分:1)

使用绑定(如@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);
    }
}

或..使用A CLOSURE

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);
    }

}

答案 1 :(得分:0)

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

edite 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);
    }

}