简体   繁体   中英

Is there a possiblity of accessing shadowed global variable using document or window object ( or any way )?

Is there any possible method/ways to access a globally declared variable inside a function which is shadowed by parameters or local variable??

var x = 10; //globally declared variable

(function abc(x){     // shadowing of x using parameter with same name
   console.log(x);    // prints 11  - Can I access globally declared x inside this function?
})(11)

Maybe .

In a browser, non-module context, top level variables declared with var are assigned as properties of the window object. So you might be able to access it with window.x .

Best practise is to avoid shadowing. I'm fond of using the no-shadow rule with ESLint to catch accidental shadowing.

You could use globalThis (added in ES2020)

globalThis.x = 10;

(function abc(globalThis){     // shadowing of x using parameter with same name
   console.log(x);    // prints 10
})(11)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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