因此,void
在执行传递给它的表达式后返回undefined
。尝试访问其属性时,undefined
会引发异常。那么,为什么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/
最佳答案
void
operator本身不使用括号。因此,该语句可能被解析为:
void( (0).someprop )
并从
someprop
访问Number
。而不是:(void (0)).someprop
如您所料,确实会引发错误。
关于javascript - void(0)返回 `undefined`,但允许属性访问。为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18774001/