[英]Immediately Invoked Function Expression and document ready function
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 $ 在使用jQuery的Javascript中,我可以使用立即调用的函数表达式将范围添加到函数中,并传递函数jQuery,并命名参数$
(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? 我是否还需要传递函数jQuery,并在文档就绪函数中命名参数$? 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. IIFE被立即调用,它不会等待
document
准备就绪。 So: 所以:
(function($) {
// here document is not necessarly ready
})(jQuery);
When you do $(function() { ... });
当您执行
$(function() { ... });
you are not creating an IIFE, you are just passing a function (callback) to be executed when the document
is ready. 您不是在创建IIFE,而是只是传递了准备好
document
时要执行的函数(回调)。
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 将自身作为参数传递给ready回调的事实):
jQuery(function($) {
// here, document is really ready
// and $ is obviously available (only here)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.