如何在javascript函数钩子中访问全局变量? [英] How to access global variable in function hook in javascript?

查看:140
本文介绍了如何在javascript函数钩子中访问全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

var x = 10; //global variable

var oldA = a;    

a = function a(param){

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

    return oldA(param);

}

如何解决错误?

推荐答案

您的代码适用于我,但您可能想解决 x 使用 window.x 显式地显示全局变量。

当不在浏览器环境中,或者全局对象不在的环境中时t叫窗口,试试:

Your code works fine for me, but you might want to resolve x to 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:

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

{x:undefined} object literal只是为了确保表达式不会引发错误。
我列出的所有名字都是我所知道的给予(严格说来说是无名的)全局对象,只需使用可能适用于你的情况的对象。

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.

另一方面,如果全局变量<$ c $在调用函数( a )时,可以重新分配c> x ,闭包更可取:

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 = (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...

这篇关于如何在javascript函数钩子中访问全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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