Skip to content Skip to sidebar Skip to footer

How To Access Global Variable In Function Hook In Javascript?

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 un

Solution 1:

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

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.

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

a = (function (globalX)
{
    returnfunctiona(param)
    {
        console.log(globalX);
        returnoldA(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...

Solution 2:

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

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

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

Post a Comment for "How To Access Global Variable In Function Hook In Javascript?"