我应该在 JavaScript 中使用 `void 0` 还是 `undefined`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19369023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I use `void 0` or `undefined` in JavaScript
提问by avo
Should I use void 0
or undefined
in JavaScript to unassign a value, for example:
我应该使用void 0
或undefined
在 JavaScript 中取消赋值,例如:
event.returnValue = void 0;
or
或者
event.returnValue = undefined;
回答by thefourtheye
If you are using a modern browser, (which supports javascript 1.8.5) using undefined
and void 0
would most likely yield the same result (since undefined
is made not writable), except that the void
can accept an expression as parameter and evaluate it.
如果您使用的是现代浏览器(支持 javascript 1.8.5),使用undefined
和void 0
很可能会产生相同的结果(因为undefined
不可写),除了void
可以接受表达式作为参数并对其进行评估。
In older browsers, (which do not support javascript 1.8.5) It is better to use void 0
. Look at this example:
在较旧的浏览器中,(不支持 javascript 1.8.5)最好使用void 0
. 看这个例子:
console.log(undefined);
var undefined = 1;
console.log(undefined);
It will print
它会打印
1
undefined
is actually a global property. (Its not a keyword). So, undefined can be changed, where as void
is an operator, which cannot be overridden in javascript and always returns the value undefined
. Just check this answer which I gave earlier today for a similiar question https://stackoverflow.com/a/19367635/1903116.
undefined
实际上是一个全局属性。(它不是关键字)。因此, undefined 可以更改,其中作为void
运算符,无法在 javascript 中覆盖并始终返回 value undefined
。只需查看我今天早些时候为类似问题提供的答案https://stackoverflow.com/a/19367635/1903116 即可。
Conclusion:
结论:
So, if you are concerned about compatibility, it is better to go with void 0
.
因此,如果您担心兼容性,最好使用void 0
.
回答by Zach
"void 0" is safer. "undefined" is a value, like any other. It's possible to overwrite that value with another:
“void 0”更安全。“未定义”是一个值,就像任何其他值一样。可以用另一个值覆盖该值:
undefined = 3;
That would change the meaning of your event.returnValue had you used undefined. "void" is a keyword, though, and its meaning can't be changed. "void 0" will always give the value undefined.
如果您使用 undefined,那将改变您的 event.returnValue 的含义。但是,“void”是一个关键字,它的含义不能改变。“void 0”将始终给出未定义的值。
回答by shade4159
The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).
void 运算符通常仅用于获取未定义的原始值,通常使用“void(0)”(相当于“void 0”)。在这些情况下,可以使用全局变量 undefined 代替(假设它没有被分配给一个非默认值)。
https://stackoverflow.com/a/1291950/2876804
https://stackoverflow.com/a/1291950/2876804
Just use undefined, since they will both evaluate to it.
只需使用 undefined,因为它们都会对其进行评估。