django django - 1 year ago 161
jQuery Question

JSLint error: Move the invocation into the parens that contain the function

How can i make this code jsLint Happy ?

;(function ( $, window, document, undefined ) {
//some code
})( jQuery, window, document );

It advises me to write it this way ? Will there be any difference ? What do i do ?

(function ( $, window, document, undefined ) {
//some code
}( jQuery, window, document ));

Answer Source

I'm copying my answer from the next question in the JSLint stack. Here's why Crockford says that the second way is better.


When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

To expand a little, JavaScript isn't, as we know, a strongly typed language. It's not uncommon to push a function into a variable, and, in fact, it could be more common to push a function into a var than a value from an immediately invoked anonymous function.

So it's worth having a little syntactic sugar in your code to show when you're invoking rather than setting a reference to a function.

Don't get bogged down by those that complain that it's impossible to separate Douglas Crockford's opinions from JSLint. They're right, and that's good!

In a big enough project, why would you have to disagree with him? I'm never seen Crockford require something that's objectively wrong. All of the rules in JSLint are arguably good ones, and standardization of code in shared projects is often A Very Good Thing. He's teaching you good (!bad?) habits for free. It's worth playing along.

(The leading semi-colon, I see where you're going -- defensive is good. But if everyone used JSLint... I still feel your pain there a little.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download