测试全局构造函数 |满足 jslint

Testing global constructors | Satisfy jslint

本文关键字:满足 jslint 构造函数 全局 测试      更新时间:2023-09-26
/*global
    test: true,
    equal: true,
*/
(function () {
    "use strict";
    test("each() and internals", function () {
        var globals = [
                new Array(),
                new Object(),
                new String(),
                new Number(),
                new Function(),
                new Boolean(),
                new Date(),
                new RegExp()
            ],
            ...

我正在编写一些QUnit测试,我想通过jslint。 我想使用一组全局对象,因为它们与它们的文字表示明显不同。

Jslint 不喜欢其中任何一个,除了最后 2 个。 我没有看到放松jslint肛门的选项。

是的,我希望我的功能测试通过jslint(不是jshint(。 是的,我想使用对象构造函数而不是文本进行某些测试。

失败的测试

Use the array literal notation [].
                new Array(),
line 31 character 21
Use the object literal notation {} or Object.create(null).
                new Object(),
line 32 character 21
Do not use String as a constructor.
                new String(),
line 33 character 21
Do not use Number as a constructor.
                new Number(),
line 34 character 29
The Function constructor is eval.
                new Function(),
line 35 character 21
Do not use Boolean as a constructor.
                new Boolean(),

来自 JSLint 指令

http://www.jslint.com/lint.html

JSLint 不希望看到包装器表单新 数字,新 字符串,新布尔值。

JSLint 不希望看到新的对象。请改用 {}。

JSLint 不希望看到新的数组。请改用 []。

看起来没有控制它的选项

此行为由 JSLint 源代码中的以下 switch 语句控制:

switch (c.string) {
case 'Object':
    token.warn('use_object');
    break;
case 'Array':
    if (next_token.id === '(') {
        // ...
        if (next_token.id !== ')') {
            // ...
        } else {
            token.warn('use_array');
        }
        // ...
    }
    token.warn('use_array');
    break;
case 'Number':
case 'String':
case 'Boolean':
case 'Math':
case 'JSON':
    c.warn('not_a_constructor');
    break;
case 'Function':
    if (!option.evil) {
        next_token.warn('function_eval');
    }
    break;
case 'Date':
case 'RegExp':
case 'this':
    break;
default:
    // ...
}

如您所见,除了 Function 构造函数的情况外,没有用于打开或关闭这些检查的选项。可以通过将evil选项设置为 true 来关闭该警告。

在这种情况下,可以安全地将对Array和构造函数的调用替换为其文本对应项Object。对于其他警告,您别无选择,只能忽略它们。

Jslint 怀疑你真的想这样做,因为使用构造函数会使比较意外失败:

var s1 = new String('hi');
var s2 = new String('hi');
// but s1 == s2 is false now!  Not to mention 'hi' === s1!

更多详细信息:http://jslinterrors.com/do-not-use-a-as-a-constructor/