New Dev
New Dev

Reputation: 49590

How to properly address this JSHint "Possible strict violation"

EDIT: this issue is related to JSHint, rather than JSLint - changed the tag.

The following gives me a "possible strict violation". I understand why the violation occurs - this is because of the use of this in a function that jslint doesn't believe is a method:

function Widget(name){
   this.name = name;
}

Widget.prototype.doSomething = doSomething;

function doSomething(){
   console.log(this.name + " did something");
}

Although, the following approaches solve the jslint warning, they force me into a code organization that I would rather avoid:

1) declaring the function inline:

Widget.prototype.doSomething = function (){
   console.log(this.name + " did something");
}

2) creating a wrapper function that passes this:

Widget.prototype.doSomething = function (){ return doSomething(this); };

function doSomething(self){
  // ...
}

Is there a way to organize the code to solve the issue other than using the approaches above?

Upvotes: 2

Views: 1348

Answers (1)

user229044
user229044

Reputation: 239301

The way to properly address this is in your question. Do #1:

Widget.prototype.doSomething = function (){
   console.log(this.name + " did something");
}

The whole point of linting is that it prevents you from making common mistakes in source code, and the error you're seeing is completely correct: You shouldn't ever see this mentioned in a function that is not declared on an object.

Linting has nothing to do with the way the program behaves when executed. It's not that linting doesn't "believe" that your method will be invoked on an object, it's that your source code contains a pattern known to be problematic. You can work around it all you like, but as long as the pattern is still in your source, you still have a linting problem.

If you want to ignore it, then wrap it in /*ignore jslint start*/ and /*ignore jslint end*/, but the problem will still be there.

Upvotes: 1

Related Questions