原型函数内的递归调用

Jak*_*ink 16 javascript recursion

好吧,所以我有这个原型对象Stage,除了这个递归调用之外,它的每个部分都有效.

Stage.prototype.start = function(key) {
        //var maxScrollLeft = document.getElementById("content").scrollWidth;
        $content.scrollLeft($content.scrollLeft() + this.initspeed);
        if(key < this.maxScrollLeft || key > 0) {
                setTimeout(function() {
                        this.start(key+2);
                },1); 
        }else{
                console.log("stop");
        }   
}   
Run Code Online (Sandbox Code Playgroud)

我试图使用this.start();在这个if语句中调用Stage.prototype.start.但是我总觉得 Uncaught TypeError: Object [object global] has no method 'start' 我觉得它与匿名函数中的调用有关,关于如何解决这个问题的任何想法?

PSL*_*PSL 22

this在你的匿名回调中,setTimeout指向全局对象,因为该函数没有绑定到任何地方,因此它被提升到全局范围.在这种情况下,您的回调是从window(浏览器)或global(节点等)上下文执行的,因此this指向全局范围,因为从该上下文调用该函数.有很多方法可以解决这个问题.一种简单的方法是缓存this到变量并在回调函数中使用它.

 Stage.prototype.start = function(key) {
           var self = this; //cache this here
            //var maxScrollLeft = document.getElementById("content").scrollWidth;
            $content.scrollLeft($content.scrollLeft() + this.initspeed);
            if(key < this.maxScrollLeft || key > 0) {
                    setTimeout(function() {
                            self.start(key+2); //use it to make the call
                    },1); 
            }else{
                    console.log("stop");
            }   
    }   
Run Code Online (Sandbox Code Playgroud)

小提琴

另一种方法是使用function.prototype.bind绑定上下文.

 Stage.prototype.start = function(key) {
            //var maxScrollLeft = document.getElementById("content").scrollWidth;
            $content.scrollLeft($content.scrollLeft() + this.initspeed);
            if(key < this.maxScrollLeft || key > 0) {
                    setTimeout((function() {
                            this.start(key+2); //now you get this as your object of type stage
                    }).bind(this),1);  //bind this here
            }else{
                    console.log("stop");
            }   
    }   
Run Code Online (Sandbox Code Playgroud)

小提琴