admin管理员组文章数量:1306270
Some javascript tomfoolery:
If this works
undefined = true;
then how can you revert back to set undefined
back to representing undefined
?
Sure, the easy way is to store undefined
in another variable before setting undefined
to true
. What other way can you restore undefined
?
First thought to set it back was delete undefined;
, didn't work.
Some javascript tomfoolery:
If this works
undefined = true;
then how can you revert back to set undefined
back to representing undefined
?
Sure, the easy way is to store undefined
in another variable before setting undefined
to true
. What other way can you restore undefined
?
First thought to set it back was delete undefined;
, didn't work.
-
In most browsers,
window.undefined
is not writable; even after executingwindow.undefined=true
,window.undefined
still evaluates toundefined
. See developer.mozilla/en-US/docs/Web/JavaScript/Reference/… . (undefined
is a property of the globalwindow
object, soundefined
andwindow.undefined
are equivalent.) – Mike Rosoft Commented May 30, 2018 at 10:58
2 Answers
Reset to default 8Alex's answer is the safe and practical way to ensure undefined
is really undefined.
But JS is super flexible, so for fun, if you wish to revert the global undefined
, then you can reassign window.undefined
from the safety of a new function scope:
(function () { // Create a new scope
var a; // "a" is undefined in this scope
window.undefined = a; // Set the global "undefined" to "a"
})() // Execute immediately
Taking this idea futher, you can reconfigure the above to bee:
undefined = (function () {
var a; // "a" is undefined
return a; // return "a"
})();
Or really, just this:
undefined = (function () {
return;
})();
But in fact, you don't actually need to return anything:
undefined = function(){}();
Of course, then there's also the void
operator ;-) doh!
undefined = void 0;
(function(undefined) {
// undefined is undefined again!
})();
jQuery uses this pattern.
delete
operator is best for deleting properties from objects. There are a number of things it won't work on, and using it with an Array
just sets the element to undefined
(sort of, it won't be enumerated with in
). Best to use splice()
with an Array
.
本文标签: javascriptundefinedtrue then back to undefinedStack Overflow
版权声明:本文标题:javascript - undefined = true; then back to undefined? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741818196a2399202.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论