问题描述
以下假设是否正确?
1)立即执行
(function(){
})();
2)在文档准备就绪时执行
2) execute on document ready
$(document).ready(function(){
});
3)准备文档的速记
$(function(){
});
4)准备好文档的替代速记,以避免跨脚本冲突
4) alternative shorthand for on document ready for avoiding cross script conflicts
(function($) {
})(jQuery);
推荐答案
是的,对于前3个,您的定义是正确的:)
Yes your definitions are correct, for the first 3 :)
尽管,除非需要闭包,否则语句将立即执行,没有理由像#1那样包装它(肯定有很多有效的时间需要闭包,只是请注意是否不需要...多余的.)
Though, unless you need a closure, a statement will execute immediately, no reason to wrap it like #1 has (there are certainly plenty of valid times you need a closure, just noting if you don't...it's superfluous).
数字4不正确,(function($) { })(jQuery);
与任何事件无关,它只是一个闭包,因此其中包含$ === jQuery
,因此可以使用$
快捷方式:
Number 4 however is not correct, (function($) { })(jQuery);
is not tied to any event, it's just a closure so that $ === jQuery
inside of it, so you can use the $
shortcut:
(function($) {
//You may use $ here instead of jQuery and it'll work...even if $ means
//something else outside of this closure, another library shortcut for example
})(jQuery);
这篇关于jQuery匿名函数声明的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!