In Javascript using jQuery i can add scope to the function using Immediately Invoked Function Expression and pass the function jQuery, and name the parameter $
(function ( $ ) {
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
};
}( jQuery ));
Similarly, we write document ready function as below
$(function() {
console.log( "ready!" );
// use $ variable here
});
Does that mean document ready function is already scoped?
Do i also need to pass the function jQuery, and name the parameter $ in document ready function? something like below
$(function ( $ ) {
console.log( "ready!" );
// use $ variable here
}( jQuery ));
The IIFE is invoked immediately, it won't wait for document
to get ready. So:
(function($) {
// here document is not necessarly ready
})(jQuery);
When you do $(function() { ... });
you are not creating an IIFE, you are just passing a function (callback) to be executed when the document
is ready.
If you want to do both, then use:
(function($) {
$(function() {
// here, document is really ready
// $ available here too
});
})(jQuery);
Or do it like this (using the fact that jQuery passes itself as parameter to its ready callback ):
jQuery(function($) {
// here, document is really ready
// and $ is obviously available (only here)
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.