[英]void(0) returns `undefined`, but allows property access. Why?
So void
returns undefined
after executing the expression passed to it. 因此,在执行传递给它的表达式后,
void
返回undefined
。 undefined
throws exceptions when you try to access its properties. 当您尝试访问其属性时,
undefined
会抛出异常。 So why is that void(0).prop
returns undefined
instead of crashing? 那么为什么
void(0).prop
返回undefined
而不是崩溃?
alert("void(0) => " + void(0)); // undefined
// How is it that this doesn't throw an exception?
alert("void(0).someprop => " + void(0).someprop); // undefined
// Exception, can't access property of undefined.
alert("undefined.someprop => " + undefined.someprop); // crash
The void
operator doesn't use parenthesis itself. void
运算符本身不使用括号。 So, the statement is probably being parsed as: 因此,该语句可能被解析为:
void( (0).someprop )
And accessing someprop
from the Number
. 并从
Number
访问someprop
。 Rather than as: 而不是:
(void (0)).someprop
As you were probably expecting, which does throw an error. 正如您可能期待的那样,这会引发错误。
void
is an operator , it is NOT a function. void
是一个运算符 ,它不是一个函数。
void(0)
is equivalent to "void 0"
. void(0)
相当于"void 0"
。
So void(0).someprop
is equivalent to void 0..someprop
. 所以
void(0).someprop
相当于void 0..someprop
。
To prove, 证明,
void(undefined).someprop
throws an error, since it will be evaluated as ( someprop
doesn't exist in undefined
for sure) 抛出一个错误,因为它将被评估为(
someprop
在undefined
中不存在肯定)
void undefined.someprop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.