简体   繁体   English

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

[英]How to access global variable in function hook in javascript?

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? 如何解决错误?

Your code works fine for me, but you might want to resolve x to the global variable explicitly by using window.x . 您的代码对我来说很好,但您可能希望使用window.x明确地将x解析为全局变量。
When not in a browser environment, or an environment where the global object isn't called window , try: 如果不在浏览器环境中,或者全局对象未被称为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. {x:undefined}对象文字只是为了确保表达式不会引发错误。
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. 我已经列出了我所知道的所有名称(严格来说都是无名的)全局对象,只使用那些可能适用于你的情况的名字。

On the other hand, if the global variable x might be reassigned by the time the function ( a ) gets called, a closure would be preferable: 另一方面,如果函数( a )被调用时可能会重新分配全局变量x ,那么闭包将是更可取的:

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... 这就是我能想到的,你的代码出了问题,更多细节可能会为我们提供实际发生的事情的线索......

To access global Js variable inside function, don't use Var in function scope and mention var in global scope. 要在函数内部访问全局Js变量,请不要在函数范围中使用Var并在全局范围中提及var。 Eg. 例如。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM