Javascript包装匿名函数内的代码 [英] Javascript wrapping code inside anonymous function
问题描述
我需要帮助理解jQuery插件创作的这种模式。有人可以为我解释一下这段简单的代码吗?
I need help understanding this pattern for jQuery plugin authoring. Can somebody explain this simple bit of code for me?
(function($) { /* Code here */ })(jQuery);
我知道这是为了避免与使用相同 $ <的不同插件发生冲突/ code>字符,但不知何故无法理解它是如何工作的。参数
$
与已解析的 jQuery
对象有什么关系?
I know this is to avoid conflict with different plugins using the same $
character but somehow cannot get around my head to understand how it works. What relation does the parameter $
has to the jQuery
object that got parsed in?
推荐答案
让我们打破这个:
(function($) { /* Code here */ })(jQuery);
首先,构造:
(function() {})();
创建一个立即执行的函数表达式(通常称为IIFE)。这是一个立即执行而不是现在定义的函数,但稍后调用。它本质上是一个匿名(未命名)函数,它被定义然后立即执行。
creates an immediately executed function expression (often called IIFE). This is a function that is executed immediately rather than defined now, but called later. It is essentially an anonymous (unnamed) function that is defined and then executed right away.
然后,将jQuery传递给它:
Then, passing jQuery to it like this:
(function() {})(jQuery);
将jQuery作为该立即执行函数的第一个参数传递。然后,将第一个参数命名为 $
,将函数内部的符号定义为与传递的第一个参数对应。
passes jQuery as the first argument to that immediately executed function. Then, naming that first argument as $
defines that symbol inside the function to correspond to the first argument that is passed.
(function($) {})(jQuery);
以展开形式显示如下:
(function($) {
// you can use $ here to refer to jQuery
})(jQuery);
jQuery插件有一些好处作者:
There a couple nice thing about this for jQuery plugin authors:
-
IIFE创建一个本地函数上下文,因此您可以为插件提供全局变量,但实际上并不是全局变量,因此不会污染或与实际的全局变量命名空间冲突。
The IIFE creates a local function context so you can have variables which are "global" for your plug-in, but are not actually global variables and thus don't pollute or conflict with the actual global variable namespace.
您可以使用 $进行编程
对于jQuery,无论主机程序是否实际具有为jQuery定义的,因为您已在函数中本地定义了 $
。
You can program with $
for jQuery, whether or not the host program actually has that defined for jQuery because you've defined $
locally within your function.
这篇关于Javascript包装匿名函数内的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!