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

1.2k views Asked by At

I took the output of some compiled TypeScript (also tried with CoffeeScript) and put it into WebStorm. When I do, JSHint complains "'Snake' is already defined" for the inner declaration of the Snake function.

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);

I can disable the warning with /*jshint -W004 */, but it seems like the warning is invalid since we are scoped within a function.

Now the weird part. If I move the __extends call down to after the function declaration, the error disappears.

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

I really have 2 questions, but the first is my main question which I will award my answer to.

  1. Is this warning valid?
  2. What are the ramifications of moving the __extends call down below the function declaration?
1

There are 1 answers

0
Snekse On

It seems like it might be complaining because the inner variable is shadowing an outer variable of the same name which could be potentially confusing.

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

According to this other SO answer, a commit was made in July 2013 around this behavior. Douglas Crockford stated (about JSLint)

JSLint now warns when a var is defined that has the same name as something in the outer scope. This is confusing because the reader cannot easily tell which variable he is looking at. It is sometimes an error because the new variable is accidentally hiding the old one. In some cases, the old one is the one intended.