I had a thought to do something like this:
(function(window, undefined){
$开发者_开发问答 = window.jQuery;
$(function(){
// Do some stuff
});
})(this);
Would you consider this good practice or bad? Does it have any implications for when jQuery(document).ready() would fire?
Only reason I'd say would be if you have some javascript to run before the DOM is ready, and you don't want to pollute the global namespace.
(function(window, undefined){
var $ = window.jQuery;
// create some variables and/or functions that shouldn't be global
// ...and do some work before the "ready()" fires
var a = 'some value';
function b() {
// do some important stuff
}
var c = b();
// Maybe set up a `.live()` handler, which doesn't rely on DOM ready.
$('.someSelector').live( function() {
// Some handler code.
// This works before DOM is ready.
});
$(function(){
// Your DOM ready code
});
})(this);
It's not needed. Using a self executable function creates a scope which makes so the variable you create into that scope do not become global.
var a = 'Hi';
alert(window.a); // "Hi"
(function () {
var a = 'Hi';
})();
alert(window.a); // "undefined"
In the case of jQuery, it's not needed. The ready function creates a scope already.
精彩评论