JSLint抱怨重新定义undefined

问题描述 投票:5回答:4

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";我只是想知道为什么这种方法不起作用。

javascript jslint reserved-words
4个回答
5
投票

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

尝试使用JSHint(为了更加理智)。


17
投票

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

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


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

根据MDN,它实际上不是JavaScript中的保留字,可以重新定义。


-2
投票

undefined是一个保留字。这就像试图命名变量falsetrue。您传递给函数的价值:

function(undefined) {...}

需要被命名为其他东西,比如

function(myVariable) {...}

UPDATE

看起来它可能实际上没有被保留为I originally read但也许它只是JSLint认为应该保留的术语......

© www.soinside.com 2019 - 2024. All rights reserved.