javascript - 原型(prototype)函数内的递归调用

标签 javascript recursion

好吧,我有了这个原型(prototype)对象 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");
        }   
}   

我正在努力使 Stage.prototype.start 在此 if 语句中被调用,使用 this.start();但是我总是得到 未捕获的 TypeError:对象 [object global] 没有方法“开始” 我认为这与匿名函数中的调用有关,关于如何解决这个问题有什么想法吗?

最佳答案

this 在 setTimeout 的匿名回调中指向全局对象,因为该函数未绑定(bind)到任何地方,所以它被提升到全局范围。在这种情况下,您的回调是从 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");
            }   
    }   

Fiddle

另一种方法是使用 function.prototype.bind 绑定(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");
            }   
    }   

Fiddle

关于javascript - 原型(prototype)函数内的递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994712/

相关文章:

javascript - 正则表达式 |闰年等等

javascript - 如何使用 jQuery 根据数组中的单词检查文本字段值?

python - 为什么我的递归冒泡排序不起作用?

algorithm - 解决以下重现: T(n) = T(n/3) + T(n/2) + sqrt(n)

algorithm - 该算法生成所有可能的有效括号的时间复杂度是多少?

file - 在 Kotlin 中递归列出文件

python - 如何在递归函数 Python 中使用列表?

javascript - Safari 中可用的默认字体

javascript - 如何使用 Angular Js 自动运行 Colorbox

javascript - 在重新加载页面javascript中保存值