是JSHint“;已定义“;IIFE模块内部的错误确实有效

Is JSHint "is already defined" errors inside of IIFE modules really valid?

本文关键字:错误 内部 有效 IIFE JSHint 定义 模块      更新时间:2024-06-16

我获取了一些已编译的TypeScript的输出(也尝试过CoffeeScript),并将其放入WebStorm中。当我这样做时,JSHint抱怨Snake函数的内部声明"已经定义了‘Snake’"。

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.move = function (meters) {
        alert(this.name + " moved " + meters + "m.");
    };
    return Animal;
})();
var Snake = (function (_super) { 
    __extends(Snake, _super);
    function Snake(name) { //Warning registered here
        _super.call(this, name);
    }
    Snake.prototype.move = function () {
        alert("Slithering...");
        _super.prototype.move.call(this, 5);
    };
    return Snake;
})(Animal);

我可以使用/*jshint -W004 */禁用警告,但警告似乎是无效的,因为我们在一个函数中起作用。

现在是奇怪的部分。如果我将__extends调用向下移动到函数声明之后,错误就会消失。

function Snake(name) {
    _super.call(this, name);
}
__extends(Snake, _super);

我真的有两个问题,但第一个是我的主要问题,我会奖励我的答案。

  1. 这个警告有效吗
  2. __extends调用下移到函数声明下面会产生什么后果

它似乎在抱怨,因为内部变量正在跟踪同名的外部变量,这可能会令人困惑。

https://stackoverflow.com/a/17852430/378151

根据另一个SO的回答,2013年7月围绕这一行为做出了承诺。Douglas Crockford表示(关于JSLint)

JSLint现在在定义与外部范围内的东西。这是令人困惑的,因为读者无法轻易判断他在看哪个变量错误,因为新变量意外地隐藏了旧变量。在里面在某些情况下,旧的是预期的。