JSLint抱怨重新定义undefined

kev*_*nji 5 javascript jslint reserved-words

undefined在技​​术上可以重新定义,所以它不是一个保留字.因此,我通常在匿名函数中编写代码,强制undefined成为未定义的变量,如下所示:

(function (undefined) {
    "use strict";
    var o = {
        test: "testvalue"
    };
    if (o.test === undefined) {
        // Do stuff here
    } else {
        // Do other stuff there
    }
}());
Run Code Online (Sandbox Code Playgroud)

但是,JSLint提到了以下错误:

Problem at line 1 character 15: Expected an identifier and instead saw 'undefined' (a reserved word).
Run Code Online (Sandbox Code Playgroud)

undefined当代码可以随意重新定义变量时,为什么JSLint会抱怨成为一个保留字?我知道你可以用typeof x === "undefined"; 我只是想知道为什么这种方法不起作用.

小智 17

'undefined' 在2009年12月发布的ECMA-262 Edition 5 Section 15.1.1.3中被声明为全局对象的不可变属性.

通过在函数中使用'undefined'作为参数名称,您试图使用传递给函数的任何内容来改变它.从技术上讲,错误在于浏览器采用标准的速度很慢,而且JSLint是正确的.

  • 你没有改变任何东西,你在顶部添加一个范围,它有一个名为`undefined`的单独变量(也是未定义的). (2认同)

Jam*_*mes 5

你的方法确实有效.仅仅因为JSLint不喜欢它并不会使它成为一个主要的罪恶.

尝试使用JSHint(更加理智).