What is benefit of using (function(){…})() in JavaScript

旧城冷巷雨未停 提交于 2019-12-10 02:36:26

问题


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?


回答1:


It creates a closure to prevent conflicts with other parts of code. See this:

  • http://docs.jquery.com/Plugins/Authoring

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);



回答2:


It creates a scope for variables, in particular defining $ for example to bind to jQuery, no matter what other libraries overwrite it. Think of it as an anonymous namespace.




回答3:


With self invoking anonymous function you create a local scope, it's very efficient and it directly calls itself.

You can read about it here




回答4:


It's just like:

var foo = function(){var l=this,g,y=l.jQuery,p=l.$,...};
foo();

But more simple and do not need a global variable.




回答5:


It allows to have local variables and operations inside of the function, instead of having to transform them to global ones.



来源:https://stackoverflow.com/questions/2235163/what-is-benefit-of-using-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!