我应该在JavaScript中使用`void 0`或`undefined` [英] Should I use `void 0` or `undefined` in JavaScript
问题描述
我应该在JavaScript中使用 void 0
或 undefined
取消分配值,例如:
Should I use void 0
or undefined
in JavaScript to unassign a value, for example:
event.returnValue = void 0;
或
event.returnValue = undefined;
推荐答案
如果您使用的是现代浏览器,(支持javascript 1.8.5)使用 undefined
和 void 0
很可能是相同的(因为 undefined
不可写),除了 void
可以接受表达式作为参数并进行评估。
If you are using a modern browser, (which supports javascript 1.8.5) using undefined
and void 0
would most likely the same (since undefined
is made not writable), except that the void
can accept an expression as parameter and evaluate it.
在较旧的浏览器中,(不支持javascript 1.8.5)最好使用 void 0
。看看这个例子:
In older browsers, (which do not support javascript 1.8.5) It is better to use void 0
. Look at this example:
console.log(undefined);
var undefined = 1;
console.log(undefined);
它将打印
1
undefined
实际上是一个全球财产。 (它不是关键字)。因此,可以更改undefined,其中 void
是一个运算符,不能在javascript中重写并始终返回值 undefined
。请查看我今天早些时候给出的一个类似问题的答案 https://stackoverflow.com/a/19367635/1903116 。
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.
结论:
所以,如果您担心兼容性,那么最好使用 void 0
。
So, if you are concerned about compatibility, it is better to go with void 0
.
这篇关于我应该在JavaScript中使用`void 0`或`undefined`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!