简体   繁体   English

为什么不为undefined分配值会在现代浏览器中产生错误?

[英]Why doesn't assigning a value to undefined produce an error in modern browsers?

For example imagine the following expression: 例如,想象以下表达式:

undefined = "whatever";

The value of undefined isn't change by this, but it doesn't produce any error or exception whatsoever either, neither in Firefox, Chrome, Edge nor IE11. undefined的值不会因此而改变,但它也不会产生任何错误或异常,无论是在Firefox,Chrome,Edge还是IE11中。

Actually the value of the expression is even the assigned value instead of undefined : 实际上,表达式的值甚至是赋值而不是undefined

var x = (undefined = "whatever");

Now x holds the value "whatever" . 现在x保持值"whatever"

This seems weird on the one hand, but worse, a source for bugs on the other hand because nobody should even attempt to redefine undefined , and typos that result in doing so should be caught by the engine. 这一方面看起来很奇怪,但更糟糕的是,另一方面,因为没有人应该尝试重新定义undefined错误来源,并且导致这样做的错别字应该被引擎捕获。 Why would that fly? 为什么那会飞?

Compare to the behavior when trying to redefine other keywords, for example: 试图重新定义其他关键字, 例如当比较的行为:

for = 12345;

This yields "Uncaught SyntaxError: Unexpected token =" as it rightly should. 这会产生"Uncaught SyntaxError: Unexpected token ="因为它应该正确。

Because js has to be backwards compatible and at some time it was introduced that way. 因为js必须向后兼容,并且在某个时候它是以这种方式引入的。 To tackle this problem strict mode was introduced. 为了解决这个问题,引入了严格模式。 While using strict mode undefined = "whatever" will throw an error. 使用严格模式时undefined = "whatever"会抛出错误。

Reading from MDN : MDN阅读:

While it is possible to use it as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug. 虽然可以在全局范围以外的任何范围内将其用作标识符(变量名)(因为undefined不是保留字),但这样做是一个非常糟糕的想法,会使您的代码难以维护和调试。

 (function () { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); 

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

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