jQuery匿名函数声明的含义 [英] jquery anonymous function declaration meanings

查看:63
本文介绍了jQuery匿名函数声明的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下假设是否正确?

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匿名函数声明的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆