繁体   English   中英

是否有可能使用文档或 window object (或任何方式)访问阴影全局变量?

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

是否有任何可能的方法/方式来访问被参数或局部变量遮蔽的 function 中的全局声明变量?

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)

也许

在浏览器中,非模块上下文中,用var声明的顶级变量被分配为window object 的属性。 因此,您可以使用window.x访问它。

最佳做法是避免阴影。 我喜欢使用 ESLint 的无阴影规则来捕捉意外阴影。

您可以使用globalThis (在 ES2020 中添加)

globalThis.x = 10;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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