什么是在JavaScript中使用(function(){...})()的好处 [英] What is benefit of using (function(){...})() in JavaScript
问题描述
我注意到在JQuery中使用了以下代码结构
(function(){var l = this,g,y = l .jQuery,p = l。$,...})()
这似乎创建了一个函数, / p>
使用这种方法相对于内联函数的内容有什么好处?
它创建一个闭包以防止与代码的其他部分冲突。请参阅:
特别方便,如果您有其他库使用 $()
方法,你必须保留与jQuery一起使用的能力。然后你可以创建一个如下的闭包:
(function($){
// $ available here
})(jQuery);
I noticed in JQuery that the following code structure is used
(function(){var l=this,g,y=l.jQuery,p=l.$,...})()
Which seems to create a function, and call it.
What is the benefit of taking this approach versus having the contents of the function inline?
It creates a closure to prevent conflicts with other parts of code. See this:
Particularly handy if you have some other library that uses the $()
method and you have to retain the ability to use that with jQuery also. Then you can create a closure such as this:
(function($) {
// $() is available here
})(jQuery);
这篇关于什么是在JavaScript中使用(function(){...})()的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!