How to access global variable in hook function in javascript?

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

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?

+4
source share
2 answers

Your code works fine for me, but you can resolve the x global variable explicitly with window.x .
If not in a browser environment or an environment where the global object is not called window , try:

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

The literal object {x:undefined} intended only to ensure that the expression does not cause errors.
I have listed almost all the names that I know that apply to the (strictly speaking, nameless) global object, just use the ones that may apply to your case.

On the other hand, if the global variable x can be reassigned by the time the function ( a ) is 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 are in strict mode, you also need to be careful with implied globals.
That all I can think of is wrong with your code, some details may give us a clue as to what is actually happening ...

+9
source

To access the global Js internal variable inside a function, do not use Var in the function area and specify var in the global area. For instance.

 <script> var foo = "hello"; function fxn() { alert(foo); foo = "bai"; } fxn(); alert(foo+"out side");</script> <script> 
0
source

Source: https://habr.com/ru/post/1488667/


All Articles