获取“RangeError:超出最大调用堆栈大小”错误

时间:2013-05-17 11:53:57

标签: javascript loops callback

如何在现有功能的基础上添加功能?

我正在使用以下方式,它在resources.onload

上给出了错误
    resource = document.getElementById(this.id);

    if (resource && resource.getAttribute('data-loading'))
    {           
        onloadOthers = resource.onload;
        onloadThis   = this.onComplete.bind(this);

//following line give error

        resource.onload = function () { // callback loops again and again!!!!!!
            if (typeof onloadOthers == "function")
                onloadOthers();
            onloadThis();
        };

        return; // just added another callback, no need to add it again.
    }
    else if (resource)
    {           
        this.onComplete();
        return; // already exist
    }

    if (this.type == "js")
    { //if filename is a external JavaScript file
        var code = document.createElement('script');
        code.setAttribute("type", "text/javascript");
        code.setAttribute('data-loading', 'yes');
        code.setAttribute("src", this.file);
        code.onload = this.onComplete.bind(this);
        code.onreadystatechange = code.onload; // ie fix
    }

1 个答案:

答案 0 :(得分:1)

通过添加var关键字前缀,将onloadOthersresources变量移到新的闭包中。

目前,您的代码“回收”这些(全局)变量,因为它们是在非本地范围内声明的:

var onloadOthers;
function func() {
    onloadOthers = ...;
    resource.onload = function() {
        onloadOthers(); // Calls the global `onloadOthers` function.
    };
}
func(); // Defines `onloadOthers`
func(); // Overwrites `onloadOthers`

通过将变量移动到局部范围,函数的所有实例都将具有“自己的”onloadOthers变量,从而解决问题。

如果您想了解有关此主题的更多信息,请阅读How do JavaScript closures work?