質問

I already know about the advantages of wrapping your Javascript in a function like this:

(function () {
    // code goes here
}())

But I've seen some scripts which accomplish this by passing the wrapper function to the jQuery object:

$(function () {
    // blah blah blah blah blah
});

What's the advantage of doing it this way, or is it just a matter of personal taste? And does doing it the second way negate the need for $(document).ready()?

役に立ちましたか?

解決

The first one

(function () {
    // code goes here
}())

That is self executing function.

And the second function is jquery specific.

If you see the docs

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

The .ready() method is typically used with an anonymous function:

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
     // Handler for .ready() called.
    });

他のヒント

Your first example is just standard JavaScript a self executing function, the second one is jQuery specific, and is a shortcut for $(document).ready(function () {});

see the jQuery documentation

and also this question for more info on self executing functions

(function(){}()) is an IIFE (Immediately-Invoked Function Expression) and is just an function executing Immediately
$(function(){}) is an jQuery callback fro when the browser is ready

i often have to add jQuery to sites that have mootools on them so to avoid $ conflicts i do somthing like this:

;(function($, app, undefined){
    // code here
}(jQuery, myApp = window.myApp || {}))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top