(function(){})()构造如何工作以及人们为什么使用它? [英] How does the (function() {})() construct work and why do people use it?
问题描述
(function(){})()
及其特定于jQuery的堂兄(function($){})(jQuery)
一直在Javascript代码中弹出。
(function() {})()
and its jQuery-specific cousin (function($) {})(jQuery)
pop up all the time in Javascript code.
这些结构如何工作,以及它们解决了哪些问题?
How do these constructs work, and what problems do they solve?
示例赞赏
推荐答案
随着JavaScript框架的日益普及, $
签名在很多不同场合使用。因此,为了减轻可能的冲突,你可以使用这些结构:
With the increasing popularity of JavaScript frameworks, the $
sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:
(function ($){
// Your code using $ here.
})(jQuery);
具体来说,这是匿名函数声明,立即执行 传递主jQuery对象作为参数。在该函数中,您可以使用 $
来引用该对象,而不必担心其他框架也在范围内。
Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $
to refer to that object, without worrying about other frameworks being in scope as well.
这篇关于(function(){})()构造如何工作以及人们为什么使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!