简体   繁体   English

void(0)返回`undefined`,但允许属性访问。为什么?

[英]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

http://jsfiddle.net/bFhLS/ http://jsfiddle.net/bFhLS/

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) 抛出一个错误,因为它将被评估为( somepropundefined中不存在肯定)

void undefined.someprop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM