开发者

How do I address the JSLint warning "Do not use 'new' for side effects"?

Why do I get these errors?

Problem at line 329 character 60: Do not use 'new' for side effects.

new widget.StyledDropdown(dojo.byId("sTitle"));

Problem at line 330 character 61: Do not use 'new' for side effects.

new widget.Styl开发者_开发百科edDropdown(dojo.byId("sSuffix"));

Problem at line 336 character 57: Do not use 'new' for side effects.

true,{shortenName : true,maxChars : 20});

Problem at line 338 character 129: Do not use 'new' for side effects.

new widget.StyledDropdown(dojo.byId("sCountry"),USPS.Address.countrySw...


You're not storing a reference to the newly-created objects, which is a code smell.

JSLint is saying "You're creating some objects but immediately discarding them; the only possible reason you can be doing that is that the act of creating the objects has side-effects, which is weird."

You can lose the warning either by preventing your constructors having side effects (which will mean finding some other way of doing whatever it is they're doing, eg. by moving that code into a normal function) or by storing references to the newly-created objects (even in a temporary local variable that you discard).


Rethinking the strategy is best, but more often, handling tech debt during a development cycle isn't an option.

If you are using JSHint you can override this option on a case by case basis. Add this jshint comment in the scope of the offending code.

/* jshint -W031 */
new widget.StyledDropdown(dojo.byId("sTitle"));
new widget.StyledDropdown(dojo.byId("sSuffix"));
...

Inline configurations are function scoped. So anything outside the scope of the comment will still be checked.


I use the following solution. It relies on using the new keyword and overriding ESLint - but that override is scoped down to the file which contains the class.

What's important is that the class is private and what is exported is a plain function. Then when you use the function in the code, it's clear that it's not a class - it's just a regular function.

This way you can still use the class syntax w/o adding new code smell.

class SideEffects {
  constructor() {
  
  }
  // ...
}

export function addSideEffects() {
  // eslint-disable-next-line no-new
  new SideEffects();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜