MDN文档指出:
Reserved words actually only apply to Identifiers (vs. IdentifierNames) . As described in es5.github.com/#A.1, these are all IdentifierNames which do not exclude ReservedWords
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords
但是,保留关键字列表不包括标识符Infinity
,NaN
和undefined
。
这些看起来确实像是关键字。为什么将它们称为标识符而不是保留关键字?
它们都是全局对象的属性,但是没有保留;您可以在语法上自由地声明具有这些名称的变量(只要您不在顶层-顶层,标识符引用全局对象上的值,并且不能重新分配):
console.log(
window.hasOwnProperty('undefined'),
window.hasOwnProperty('NaN'),
window.hasOwnProperty('Infinity'),
);
(() => {
const undefined = 'foo';
const NaN = 'bar';
const Infinity = 'baz';
console.log('No error');
})();
另一方面,保留的关键字不能用作标识符(变量名)。
undefined
,NaN
和Infinity
实际上是全局对象的properties。
查看我的完整答案here
除了“ CeromePerformance答案,它们是普通变量,它们也可以在代码块中限定范围:
console.log(undefined, NaN, Infinity);
(() => {
(() => {
const undefined = 'foo1';
const NaN = 'bar1';
const Infinity = 'baz1';
console.log(undefined, NaN, Infinity);
})();
const undefined = 'foo';
const NaN = 'bar';
const Infinity = 'baz';
console.log(undefined, NaN, Infinity);
})()