【问题标题】:Strange recursive infinite loop I cannot track down奇怪的递归无限循环我无法追踪
【发布时间】:2010-03-29 13:42:28
【问题描述】:

我有一个原型,它有一个可以添加回调的方法:

/*
 * Add a callback function that is invoked on every element submitted and must return a data object.
 * May be used as well for transmitting static data.
 * 
 * The callback function is supposed to expect a jQuery element as single parameter 
 * and must return a data object (for additional data to be sent along with the one already given upon initialization).
 * Adding multiple callback functions results in those functions being invoked in the same order as they were added.
 * 
 * 1) Therefore subsequent assignments to the same key in the data array override those that were performed by a previous callback function.
 * 2) If data_arg = true is given, the data returned by the callback function that was previously called is given to the new_callback as 2nd argument, so it can be manipulated.
 *    However, even if it isn't, the unchanged data must be returned anyway to have any effect.
 */

this.add_data_callback = function(new_callback, data_arg) {

    if(this.data_callback) {
        old_callback = this.data_callback;

        if(!data_arg) {
            //alert('add it');
            //alert(old_callback);
            //alert(new_callback);

            this.data_callback = function(element) {
                //alert('do it');
                //alert(old_callback);
                //alert(new_callback);
                return jQuery.extend(old_callback(element), new_callback(element));
            };
        }
        else {
            this.data_callback = function(element, data) {
                return new_callback(element, old_callback(element));
            };
        }
    }
    else {
        //alert('add the first');
        //alert(new_callback);
        this.data_callback = new_callback;
    }
};

(请忽略 data_arg = true 的 else 部分,因为它不相关。)

在我的具体案例中,我添加了三个回调函数。但是,如果最终为元素调用 this.data_callback() ,则会导致整个事物无限循环。 在我试图追踪错误的过程中,上面的警报(是的,我知道有调试工具,但这样更舒服)提供了对问题的以下见解:

  1. 调用匿名函数/闭包(包含 jQuery.extend() 的那个)。 new_callback 包含第三个回调函数。 old_callback 包含另一个...
  2. 被调用的匿名函数。 new_callback 包含第二个回调函数。 old_callback 应该包含第一个回调函数,但实际上它是另一个......
  3. 被调用的匿名回调。 new_callback 再次包含第二个回调函数。 old_callback 包含匿名函数
  4. ...

现在,我错过了什么?是一些奇怪的关闭魔法还是只是一些我显然看不到的明显错误?

提前致谢!

【问题讨论】:

    标签: javascript jquery recursion closures infinite-loop


    【解决方案1】:

    为什么old_callback 不是用var 定义的?

    var old_callback = this.data_callback;
    

    事实上,它是一个全局变量。也许它已在其他地方声明,但对我来说仍然很可疑。

    【讨论】:

    • this关键字的使用来看,发布的代码看起来像是类的一部分,而old_callback可能是该类的私有属性。
    • 哈!好吧,缺少var 是一个困扰每个人的守护进程!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2017-05-23
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多