0

Getting warning for unexpected this warning

Date.prototype.addHours = function (h) {
        this.setTime(this.getTime() + (h * 60 * 60 * 1000));
        return this;
    };
Shashwat Tripathi
  • 572
  • 1
  • 5
  • 19
  • 1
    That's just a default setting in JSLint. Your use of `this` there is *perfectly fine*, Crockford just doesn't like it. You can tell it not to do that by telling it to "tolerate `this`". See the linked question's answers for details. (For a slightly less opinionated tool, you might look at http://jshint.com/.) – T.J. Crowder Apr 18 '17 at 12:43
  • Yeah, that is also one option but what if I don't want to suppress this warning by using this JSLint directive. – Shashwat Tripathi Apr 18 '17 at 12:46
  • 1
    Then you don't use `this`, and cannot enhance the prototype of `Date` (at least, not in a useful way, since you can't use `this`). Crockford is a zealot in this regard. See the documentation: http://jslint.com/help.html#this – T.J. Crowder Apr 18 '17 at 12:49
  • I can create a separate function and pass it a date object and add hours to it, but that way I can't attach addHours to Date prototype :-( – Shashwat Tripathi Apr 18 '17 at 12:55
  • Right. :-) (Okay, *zealot* may be strong, but he's highly-opinionated on the topic of `this` [and many other things]. Some of those opinions are mainstream. Some of them are not.) Crockford doesn't like constructor functions, its one of the ways he's at odds with most of the JavaScript world. Passing the date object into another function is how he would handle the function above. – T.J. Crowder Apr 18 '17 at 12:56

0 Answers0