javascript 匿名函数中的Javascript包装代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19610586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript wrapping code inside anonymous function
提问by Mintz
I need help understanding this pattern for jQuery plugin authoring. Can somebody explain this simple bit of code for me?
我需要帮助来理解 jQuery 插件创作的这种模式。有人可以为我解释一下这个简单的代码吗?
(function($) { /* Code here */ })(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?
我知道这是为了避免与使用相同$
字符的不同插件发生冲突,但不知何故我无法理解它是如何工作的。参数$
与jQuery
解析的对象有什么关系?
回答by jfriend00
Let's break this down:
让我们分解一下:
(function($) { /* Code here */ })(jQuery);
First, the construct:
首先,构造:
(function() {})();
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.
创建一个立即执行的函数表达式(通常称为 IIFE)。这是一个立即执行而不是现在定义的函数,而是稍后调用。它本质上是一个匿名(未命名)函数,它被定义然后立即执行。
Then, passing jQuery to it like this:
然后,像这样将 jQuery 传递给它:
(function() {})(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.
将 jQuery 作为第一个参数传递给立即执行的函数。然后,将第一个参数命名为$
在函数内定义该符号以对应于传递的第一个参数。
(function($) {})(jQuery);
which in expanded form looks like this:
其展开形式如下所示:
(function($) {
// you can use $ here to refer to jQuery
})(jQuery);
There a couple nice thing about this for jQuery plugin authors:
对于 jQuery 插件作者来说,这有几个好处:
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.
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.
IIFE 创建了一个局部函数上下文,因此您可以拥有对插件来说是“全局”的变量,但实际上不是全局变量,因此不会污染或与实际的全局变量命名空间冲突。
您可以使用
$
for jQuery进行编程,无论主机程序是否确实为 jQuery 定义了该定义,因为您已$
在函数中本地定义。
回答by Niet the Dark Absol
What you have there is shorthand for something like this:
你有什么是这样的简写:
function anonymous_function($) {
// Code here
};
anonymous_function(jQuery);
As you can see, it allows the $
symbol to be used as a reference to the jQuery
object inside the function.
如您所见,它允许将$
符号用作jQuery
对函数内部对象的引用。
回答by Sean Vieira
A function in JavaScript can be either a statement or an expression. When you use a function expression, you can pass it around like any other value:
JavaScript 中的函数可以是语句或表达式。当您使用函数表达式时,您可以像传递任何其他值一样传递它:
> console.log(function() { 1 + 1; });
> (function() {}) && doExpensiveWork();
// etc.
One of the things you can do with a function expression is immediately invoke it. In such cases the function is called an immediately invoked function expression (or IIFE for short):
您可以使用函数表达式做的一件事是立即调用它。在这种情况下,该函数被称为立即调用的函数表达式(或简称 IIFE):
> (function() { console.log("IIFE running"); })();
IIFE running
This is the same as creating the function and invoking it in two steps:
这与创建函数并分两步调用它是一样的:
> var notAnIIFE = function() { console.log("running"); };
> notAnIIFE();
running
A function expression can, of course, take arguments:
函数表达式当然可以带参数:
> var someFunction = function(x, y) { return x + y; };
> var seven = someFunction(3, 4);
> seven
7
So an IIFEcan be invoked with arguments as well:
所以IIFE也可以用参数调用:
> var seven = (function(x, y) { return x + y; })(3, 4);
> seven
7
In the case of an invocation like this:
在这样的调用的情况下:
(function($) { /* do work with $ */ })(jQuery);
the value bound to the name jQuery
is being passed into the function expression as the argument $
. This is similar to doing the following:
绑定到名称的值jQuery
作为参数传递到函数表达式中$
。这类似于执行以下操作:
var initializePlugin = function($) {
/* do work with $ */
};
initializePlugin(jQuery);
but it leaves no trace in the parent namespace (whereas, in our second example, our initializePlugin
name is left behind after we finish setting up our plugin).
但它在父命名空间中没有留下任何痕迹(而在我们的第二个示例中,我们的initializePlugin
名字在我们完成插件设置后被留下)。
回答by Keith C
+1 for jfriend00's answer.
+1 jfriend00 的回答。
But including jQuery in a page overwrites both of the global symbols jQuery and $ (see jQuery.js line 9579) potentially causing conflicts with other libraries that define a global $.
但是在页面中包含 jQuery 会覆盖全局符号 jQuery 和 $(请参阅jQuery.js 第 9579 行),这可能会导致与定义全局 $ 的其他库发生冲突。
So taking this a step further to also stop the global $ conflict:
因此,更进一步以阻止全球 $ 冲突:
(function($) {
// you can use $ here to refer to jQuery
})(jQuery.noConflict());
as demonstrated by:
如下所示:
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
(function($) {
console.log('want $ to be jQuery here so want true: ' + ($ === jQuery));
})(jQuery.noConflict());
console.log('do not want $ to be jQuery here so want false: ' + ($ === jQuery));
</script>
回答by Michael Krelin - hacker
The function in javascript creates a scope, it's not just about the $
variable, but about variables local to the function. And given the $
parameter, it becomes local to the function and safe to use, referring to jQuery
.
javascript 中的函数创建了一个作用域,它不仅与$
变量有关,还与函数的局部变量有关。并且给定$
参数,它成为函数的局部并且可以安全使用,参考jQuery
.