javascript 如何在javascript中的函数钩子中访问全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17363548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:01:59  来源:igfitidea点击:

How to access global variable in function hook in javascript?

javascript-objectsjavascript

提问by Mmh

I want to use global variable 'x' in the below hook funcion.

我想在下面的钩子函数中使用全局变量“x”。

var x = 10; //global variable

var oldA = a;    

a = function a(param){

    alert(x);        //showing error: x is undefined 

    return oldA(param);

}

How to resolve the error?

如何解决错误?

回答by Elias Van Ootegem

Your code works fine for me, but you might want to resolve xto the global variable explicitly by using window.x.
When not in a browser environment, or an environment where the global object isn't called window, try:

您的代码对我来说工作正常,但您可能希望x通过使用window.x.
如果不在浏览器环境中,或者不在全局对象未被调用的环境中window,请尝试:

(window || root || global || GLOBAL || this || self || {x: undefined).x

The {x:undefined}object literal is just to make sure the expression doesn't throw up errors.
I've listed pretty much all names I know of that are given to the (strictly speaking nameless) global object, just use the ones that might apply to your case.

{x:undefined}对象字面是只是为了确保表达式不扔了错误。
我已经列出了几乎所有我知道的(严格来说是无名的)全局对象的名称,只需使用可能适用于您的情况的名称。

On the other hand, if the global variable xmightbe reassigned by the time the function (a) gets called, a closure would be preferable:

另一方面,如果在函数 ( ) 被调用时全局变量x可能会被重新赋值,则a最好使用闭包:

a = (function (globalX)
{
    return function a(param)
    {
        console.log(globalX);
        return oldA(param);
    };
}(x || window.x));//pass reference to x, or window.x if x is undefined to the scope

Of course, if you're in strict mode, you need to be careful with implied globals, too.
That's all I can think of that is going wrong with your code, some more details might provide us with a clue of what's actually happening...

当然,如果您处于严格模式,您也需要小心隐含的全局变量。
这就是我能想到的你的代码出了问题的全部内容,更多细节可能会为我们提供实际发生情况的线索......

回答by gnganpath

To access global Js variable inside function, don't use Var in function scope and mention var in global scope. Eg.

要访问函数内部的全局 Js 变量,请不要在函数范围内使用 Var,而在全局范围内提及 var。例如。

<script>
    var foo = "hello";
    function fxn() {
        alert(foo);
        foo = "bai";
    }
    fxn();

    alert(foo+"out side");
</script>