为什么要定义一个匿名函数并将其作为参数传递给 jQuery?

我正在查看 backbone.js 屏幕录像中出色的 peepcode 演示代码。其中,主干代码全部封装在一个传递给 jQuery 对象的匿名函数中:

(function($) {
// Backbone code in here
})(jQuery);

在我自己的主干代码中,我刚刚将所有代码包装在 jQuery DOM“ ready”事件中:

$(function(){
// Backbone code in here
});

第一种方法的重点/优点是什么?这样做会创建一个匿名函数,然后立即执行该函数,并将 jQuery 对象作为函数参数传递,从而有效地确保 $是 jQuery 对象。这是保证 jQuery 绑定到“ $”的唯一要点吗? 还是有其他理由这样做?

78745 次浏览

It is to avoid a potential conflict of the $ variable. If something else defines a variable named $, your plugin may use the wrong definition

Refer to http://docs.jquery.com/Plugins/Authoring#Getting_Started for more details

It ensures you can always use $ inside that closure even if $.noConflict() was used.

Without this closure you'd be supposed to use jQuery instead of $ the whole time.

The two blocks of code you have shown are dramatically different in when and why they execute. They are not exclusive of each other. They do not serve the same purpose.

JavaScript Modules


(function($) {
// Backbone code in here
})(jQuery);

This is a "JavaScript Module" pattern, implemented with an immediately invoking function.

The purpose of this code is to provide "modularity", privacy and encapsulation for your code.

The implementation of this is a function that is immediately invoked by the calling (jQuery) parenthesis. The purpose of passing jQuery in to the parenthesis is to provide local scoping to the global variable. This helps reduce the amount of overhead of looking up the $ variable, and allows better compression / optimization for minifiers in some cases.

Immediately invoking functions are executed, well, immediately. As soon as the function definition is complete, the function is executed.

jQuery's "DOMReady" function

This is an alias to jQuery's "DOMReady" function: http://api.jquery.com/ready/


$(function(){
// Backbone code in here
});

jQuery's "DOMReady" function executes when the DOM is ready to be manipulated by your JavaScript code.

Modules vs DOMReady In Backbone Code

It's bad form to define your Backbone code inside of jQuery's DOMReady function, and potentially damaging to your application performance. This function does not get called until the DOM has loaded and is ready to be manipulated. That means you're waiting until the browser has parsed the DOM at least once before you are defining your objects.

It's a better idea to define your Backbone objects outside of a DOMReady function. I, among many others, prefer to do this inside of a JavaScript Module pattern so that I can provide encapsulation and privacy for my code. I tend to use the "Revealing Module" pattern (see the first link above) to provide access to the bits that I need outside of my module.

By defining your objects outside of the DOMReady function, and providing some way to reference them, you are allowing the browser to get a head start on processing your JavaScript, potentially speeding up the user experience. It also makes the code more flexible as you can move things around without having to worry about creating more DOMREady functions when you do move things.

You're likely going to use a DOMReady function, still, even if you define your Backbone objects somewhere else. The reason is that many Backbone apps need to manipulate the DOM in some manner. To do this, you need to wait until the DOM is ready, therefore you need to use the DOMReady function to start your application after it has been defined.

You can find plenty of examples of this around the web, but here's a very basic implementation, using both a Module and the DOMReady function:




// Define "MyApp" as a revealing module


MyApp = (function(Backbone, $){


var View = Backbone.View.extend({
// do stuff here
});


return {
init: function(){
var view = new View();
$("#some-div").html(view.render().el);
}
};


})(Backbone, jQuery);






// Run "MyApp" in DOMReady


$(function(){
MyApp.init();
});

As a minor sidenote, sending in $ as an argument to an anonymous function makes $ local to that function which has a small positive performance implication if the $ function is called a lot. This is because javascript searches the local scope for variables first and then traverses down all the way to the window scope (where $ usually lives).

Use both.

The self invoking function in which you pass in jQuery to prevent library conflicts, and to just make sure jQuery is available as you would expect with $.

And the .ready() shortcut method as required to run javascript only after DOM has loaded:

(function($) {
$(function(){
//add code here that needs to wait for page to be loaded
});


//and rest of code here
})(jQuery);