问题描述
似乎 window.undefined
是可写的,即可以将其设置为默认值以外的其他值(毫无疑问,它是 undefined
).
It appears that window.undefined
is writable, i.e. it can be set to something else than its default value (which is, unsurprisingly, undefined
).
但是,要点是,每当我引用 undefined
时,它都引用 window.undefined
(因为在以下情况下可以删除 window
这个).
The point is however that whenever I refer to undefined
, it refers to window.undefined
(as window
can be removed in cases like this).
这么说,我实际上如何获得对 undefined
'instance'的访问?如果 window.undefined
已被更改,如何将另一个变量设置为 undefined
?
So how do I actually get access to an undefined
'instance', so to say? How would I be able to set another variable to undefined
, if window.undefined
has been changed?
如果我编码:
window.undefined = 'foo'; // This code might have been executed by someone/something
var blah = undefined; // blah is not undefined, but equals to 'foo' instead...
我怎么可能解决这个问题?
How could I possibly solve this?
推荐答案
此问题的标准"解决方案是使用内置的 void
运算符.它的唯一目的是返回undefined:
The "standard" solution to this problem is to use the built in void
operator. Its only purpose is to return undefined:
var my_undefined = void 0;
除此之外,这里还有其他获取 undefined
的方法:
In addition to this, yhere are other ways to get undefined
:
如果不执行返回
任何操作,函数将返回未定义状态,因此您可以执行类似的操作
Functions return undefined if you don't return
anything so you could do something like
this_is_undefined = (function(){}());
如果没有将足够的参数传递给函数,则也会得到未定义的信息.所以一个常见的成语是
You also get undefined if you don't pass enough arguments to a function. So a common idiom is
function foo(arg1, arg2, undefined){ //undefined is the last argument
//Use `undefined` here without worrying.
//It is a local variable so no one else can overwrite it
}
foo(arg1, arg2);
//since you didn't pass the 3rd argument,
//the local variable `undefined` in foo is set to the real `undefined`.
这种类型对于同时定义和调用函数的情况特别有用,这样您就不必担心会忘记并传递错误数量的参数.
This kind is particularly good for cases when you define and call the function at the same time so you don't have any risk of forgetting and passing the wrong number of arguments latter.
这篇关于如果"window.undefined"被覆盖,则获取"undefined"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!