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)
CodePudding user response:
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.
CodePudding user response:
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)