undefined
在技术上可以重新定义,因此它不是一个保留字。因此,我通常在匿名函数中编写代码,强制undefined
为未定义的变量,如下所示:
(function (undefined) {
"use strict";
var o = {
test: "testvalue"
};
if (o.test === undefined) {
// Do stuff here
} else {
// Do other stuff there
}
}());
但是,JSLint提到以下错误:
Problem at line 1 character 15: Expected an identifier and instead saw 'undefined' (a reserved word).
当代码可以随意重新定义变量时,为什么JSLint抱怨undefined
是一个保留字?我知道你可以使用typeof x === "undefined"
;我只是想知道为什么这种方法不起作用。
你的方法确实有效。仅仅因为JSLint不喜欢它并不会使它成为一个主要的罪恶。
尝试使用JSHint(为了更加理智)。
'undefined'在2009年12月发布的ECMA-262 Edition 5 Section 15.1.1.3中被宣布为全局对象的不可变属性。
通过在函数中使用'undefined'作为参数名称,您试图使用传递给函数的任何内容来改变它。从技术上讲,错误在于浏览器采用标准的速度很慢,而且JSLint是正确的。
(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })();
根据MDN,它实际上不是JavaScript中的保留字,可以重新定义。
undefined
是一个保留字。这就像试图命名变量false
或true
。您传递给函数的价值:
function(undefined) {...}
需要被命名为其他东西,比如
function(myVariable) {...}
UPDATE
看起来它可能实际上没有被保留为I originally read但也许它只是JSLint认为应该保留的术语......