gpt4 book ai didi

javascript - 创建一个空范围?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:49 24 4
gpt4 key购买 nike

有没有办法定义范围,使其完全为空?理想情况下,这会导致 window 未定义。还是 window 在每个范围排列中始终可用?我最初的想法是将一个空对象应用到一个闭包中,但是 window 仍然被定义:

(function() {
console.log(this); // an empty object
console.log(window); // the window object is still defined
}).apply({});

有什么方法可以绕过 window 及其相关变量,还是我现在只是觉得好笑?

最佳答案

如果您在浏览器之外执行 javascript,则不一定有窗口对象。例如,nodejs 脚本没有窗口对象,但它们有一个全局进程对象。

如果你真的不想有可用的窗口对象,你可以在新范围内用局部变量破坏它......

(function(){ var window = undefined; console.log(this); console.log(window) }).apply({});

这不会触及全局 window 对象,它不能被破坏,但应该在本地覆盖它。

一个更通用的包装器,因为内部作用域继承自外部作用域...

(function(){ var window = undefined; (function(){
console.log(this);
console.log(window);
}).apply({}); })();

编辑:为所有全局变量添加通用解决方案...

// create self invoking anonymous function
;(function(){
// enumerate all global objects (`this` refers to current scope - assumed to be global at this point)
var globals = Object.keys(this);
// loop through all globals
for(i in globals){
// don't clobber the `console` global - we will need it!
if(globals[i] !== "console"){
// initialise local variable in current scope with name of every global
eval("var " + globals[i]);
};
};
// create scope with empty object for `this` and all globals reset
;(function(){
console.log(this);
console.log(window);
/* for node.js, check process, not window ... */
// console.log(process);
}).apply({});
})();

关于javascript - 创建一个空范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21440626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com