undefined = true; 然后回到undefined?

Mik*_*keM 5 javascript undefined

一些javascript tomfoolery:

如果这样的话

undefined = true;
Run Code Online (Sandbox Code Playgroud)

那你怎么能恢复回到undefined代表undefined呢?


当然,简单的方法是undefined在设置之前存储在另一个变量undefinedtrue.还有什么方法可以恢复undefined

首先想到把它归还delete undefined;,是行不通的.

Dav*_*ang 8

亚历克斯的答案是确保实际未定义的安全而实用的方法undefined.

但JS是超级灵活的,所以为了好玩,如果你希望恢复全局 undefined,那么你可以重新分配window.undefined新功能范围的安全性:

(function () {            // Create a new scope
   var a;                 // "a" is undefined in this scope
   window.undefined = a;  // Set the global "undefined" to "a"
})()                      // Execute immediately
Run Code Online (Sandbox Code Playgroud)

进一步考虑这个想法,你可以重新配置以上内容:

undefined = (function () {
   var a;                 // "a" is undefined
   return a;              // return "a"
})();
Run Code Online (Sandbox Code Playgroud)

或者真的,就这样:

undefined = (function () {
    return;
})();
Run Code Online (Sandbox Code Playgroud)

但事实上,你实际上并不需要返回任何东西:

undefined = function(){}();
Run Code Online (Sandbox Code Playgroud)

当然,还有void运营商 ;-) doh!

undefined = void 0;
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 7

(function(undefined) {

   // undefined is undefined again!

})();
Run Code Online (Sandbox Code Playgroud)

jQuery使用这种模式.

deleteoperator最适合从对象中删除属性.有许多东西它不会起作用,并且使用它Array只是将元素设置为undefined(排序,它不会被枚举in).最好splice()用的Array.