获取“RangeError:最大调用堆栈大小超出”错误 [英] Getting the “RangeError: Maximum call stack size exceeded” error

查看:366
本文介绍了获取“RangeError:最大调用堆栈大小超出”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在已经存在的函数之上添加函数?

how can i add function on top of the already existing function?

我使用以下方式,它给我在资源的错误.onload

i'm using following way and it gives me error on 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
    }


推荐答案

onloadOthers resources .org / en-US / docs / JavaScript / Reference / Statement / varrel =nofollow> var 关键字。

Move the onloadOthers and resources variables in a new closure, by prefixing the var keyword.

目前,您的代码回收这些(全局)变量,因为它们在非本地作用域中声明:

Currently, your code "recycles" these (global) variables, because they're declared in a non-local scope:

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

通过将变量移动到局部作用域,函数的所有实例有一个自己的 onloadOthers 变量,这解决了问题。

By moving the variable to a local scope, all instances of the function will have an "own" onloadOthers variable, which solves the problem.

如果您想了解有关此主题的更多信息,请阅读 JavaScript闭包如何工作?

If you want to learn more about this topic, read How do JavaScript closures work?.

这篇关于获取“RangeError:最大调用堆栈大小超出”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆