您所展示的两个代码块在执行时间和执行原因上存在显著差异.它们并不是相互排斥的.它们的用途不同.
JavaScript模块
(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.
这是一个函数的实现,调用(jQuery)
个括号即可立即调用该函数.将jQuery传入括号的目的是为全局变量提供局部作用域.这有助于减少查找$
变量的开销,并在某些情况下为小型化程序提供更好的压缩/优化.
立即调用的函数会立即执行.函数定义一完成,函数就被执行.
jQuery的"DOMReady"函数
这是jQuery"DOMReady"函数的别名:http://api.jquery.com/ready/
$(function(){
// Backbone code in here
});
当DOM准备好被JavaScript代码操纵时,jQuery的"DOMReady"函数就会执行.
主干代码中的模块与DOMReady
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.
最好在DOMReady函数之外定义主干对象.一、 在许多其他方法中,我更喜欢在JavaScript模块模式中这样做,以便为代码提供封装和隐私.我倾向于使用"显示模块"模式(见上面的第一个链接)来提供对模块外部所需位的访问.
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.
即使您在其他地方定义了您的主干对象,您也可能会使用DOMReady函数.原因是许多主干应用程序需要以某种方式操作DOM.为此,您需要等待DOM就绪,因此需要使用DOMReady函数在定义应用程序之后启动它.
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();
});