mariovalens
mariovalens

Reputation: 365

JSHINT strict violation function expression vs function declaration

I was having trouble to get around JSHINT complaining about the usage of this keyword as a possible strict violation.

Initially I had this simple prototype pattern and I was using function declaration. In this case JSHINT throws possible strict violation

(function (ns) {
    'use strict';

    ns.EventData = function (eventData) {        
        this.id = eventData.id;
        this.name = eventData.name;
    };

    ns.EventData.prototype = (function () {        
        return {
            getDate: getDate            
        };
        // function declaration
        function getDate() {
            return ns.utils.formatDate(this.date);
        };

    }());
}(window.myProject));

However when I switched to function expression everything worked just fine. Can anyone explain why the difference ?

ns.EventData.prototype = (function () {
    // function expression
    var getDate = function () {
        return ns.utils.formatDate(this.date);
    };

    return {
        getDate: getDate            
    };
}());

Upvotes: 1

Views: 142

Answers (1)

IMujagic
IMujagic

Reputation: 1259

The thing is when you are using function declaration you can place it wherever you want. It doesn't matter if you call function before you declare it, it will be available in memory, and you will not get errors. That's how JavaScript is interpreted.

That's not the case with the expression. Expression needs to be executed before it's called (it's expression, so it makes sense). So for example you can do this:

  (function (ns) {
      'use strict';

      test();

      function test() {
          console.log('Test');
      }

  }(window.myProject));

But you can't do this:

(function (ns) {
    'use strict';

    test();

    var test = function() {
        console.log('Test');
    }

}(window.myProject));

I think that's the only difference between those two. Javascript interpreter will find and move all declarations at the top of the scope (in your case (function (ns) {...) and that's why JSHint is complaining.

Conclusion, when JSHint see that you are using this inside function declaration it will warn you because interpreter will maybe move that function to different context and you will maybe have different value for this.

That's just a warning and theoretically it's possible that something similar can happen, but in most of the cases you are pretty much sure about your namespaces and contexts, so just ignore it ;)

Upvotes: 1

Related Questions