JSLint:为什么这段代码会导致“严格模式违规”错误消息?

14

运行下面的简单代码会导致“Strict violation”错误消息。 我一直在试图找到有关为什么以及如何修复它的文档。 任何输入都将不胜感激。

错误信息:

Error:

Problem at line 6 character 4: Strict violation.

} (this));

示例代码:

/*jslint browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true */

"use strict";

(function (window) {
} (this));

问候,Egil。


1
相关吗?http://twitter.com/kangax/status/8980322050 - kennytm
KennyTM,可能是这样,请有人确认一下? - Egil Hansen
2个回答

17

对Roland Illig的答案进行补充:

在非严格模式下,当this没有绑定到其他任何内容时,则会绑定到全局范围。 在严格模式下,它是未定义的。这使得在方法外部使用它成为一种错误。


1
如果在全局环境中使用,this仍然指向全局作用域,但在严格模式下的方法中则不会。 - Qantas 94 Heavy

8

我查看了JSLint的源代码,其中写着:

function reservevar(s, v) {
    return reserve(s, function () {
        if (this.id === 'this' || this.id === 'arguments' ||
                this.id === 'eval') {
            if (strict_mode && funct['(global)']) {
                warning("Strict violation.", this);
            } else if (option.safe) {
                warning("ADsafe violation.", this);
            }
        }
        return this;
    });
}

我猜测jslint真正抱怨的是你在全局上下文中使用了this

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接