在 JavaScript 中使用 (function(){...})() 有什么好处 [英] What is benefit of using (function(){...})() in JavaScript

查看:46
本文介绍了在 JavaScript 中使用 (function(){...})() 有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在 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:

如果您有其他一些使用 $() 方法的库,并且您必须保留将其与 jQuery 一起使用的能力,则特别方便.然后你可以创建一个像这样的闭包:

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屋!

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