【问题标题】:Recursive call within prototype function原型函数内的递归调用
【发布时间】:2013-09-25 01:22:56
【问题描述】:

好的,所以我有这个原型对象 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");
        }   
}   

我试图让它在这个 if 语句中调用 Stage.prototype.start,使用 this.start();但是我总是得到 Uncaught TypeError: Object [object global] has no method 'start' 我认为这与匿名函数中的调用有关,有什么想法可以解决这个问题吗?

【问题讨论】:

    标签: javascript recursion


    【解决方案1】:

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

    Fiddle

    您可以做的另一种方法是使用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");
                }   
        }   
    

    Fiddle

    【讨论】:

      猜你喜欢
      • 2013-12-07
      • 2013-03-03
      • 2016-02-12
      • 1970-01-01
      • 2016-05-02
      • 2015-01-11
      • 1970-01-01
      • 2012-08-29
      • 2023-04-04
      相关资源
      最近更新 更多