I have a self-contained Backbone.View
implementation called MainControllerView
that can handle itself (i.e., no reason to have an outside reference to it.). If, in my main bootstrapper function I kick things off like this:
$(function() {
new MainControllerView();
});
JSLint/JSHint complain that I am using "new for side effects." Reading up on this warning indicates that the above is considered smelly code. The alternatives are to not use new at all and just invoke the constructor as a function, or to assign it to a variable. However, calling my MainControllerView()
directly as a function without using new
raises errors in the backbone code, so that's apparently not an option. And its seems totally wrong to me that the following is somehow better code:
$(function() {
var instantGarbage = new MainControllerView();
});
In fact this raises a different JSLint warning "instantGarbage is defined but never used." Apparently, I'm danged if I do and I'm danged if I don't. So, is there a different "right" way to handle this sort of thing? Is creating instant garbage variables somehow the "better code" alternative? Is Backbone.js leveraging the "new" keyword in a non-Crockford-approved way? Or is this just one of the exceptions to the "rule"?
new
is not harmful. Repeat over and over again.
If used correctly, new
works very well. Like in Backbone.
JSLint is a very opinionated linter; just because Crockford says something is bad or shouldn't be used, doesn't mean that's a universal truth. Plus, his reasoning behind it is more on the end that it obscures Javascript prototypal nature behind a more classical-oo façade.
However, if you use a tool like JSHint, you can configure these warnings.
I prefer the latter of your two declarations
$(function() {
var instantGarbage = new MainControllerView();
});
You can suppress this with the unused: false
option to JSHint.
Or you can set nonew: false
instead.
These can be set in a .jshintrc
or even per-file with a comment:
/* jshint unused: false */
At the top of your file. This will turn it off for the file. You can even disable it for specific scopes.
Check out the jshint documentation
Ok first of all Crockford is a human being with opinions; nothing more, nothing less. A great number of people disagree with many of his opinions, which is why the JSHint library is far more popular than JSLint even though JSLint had the advantage of coming first.
I'd strongly recommend switching to JSHint so that you can stop worrying about silly things that Crockford cares about that don't actually make your code worse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With