关于jquery闭包的一个简单问题 [英] a simple question on jquery closure

查看:285
本文介绍了关于jquery闭包的一个简单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么意思?

(function($){
})(jQuery);

使问题更清楚,在括号中包装函数的含义是什么意思(对不起,我'我对闭包的概念有点困惑)。 $参数怎么样?和最后括号中的jQuery?

to make the question clearer, what does wrapping a function in parenthesis mean in JS (sorry, I'm a bit confused on the concept of closures). What about the $ parameter? and the "jQuery" in the end parenthesis?

我可以用mootools做同样的事情并将它们合并到1个JS文件中吗?

Can I do the same with mootools and combine them in 1 JS file?

(function($){})(jQuery);

(function($){})(mooTools);

我只与jquery合作并计划与Mootools合作

I have only worked with jquery and am planning to work with Mootools

推荐答案

在括号之间包装函数可确保将此函数计算为函数表达式

Wrapping a function between parenthesis ensures this function to be evaluated as a function expression.

这是因为 分组操作员 (括号),只能评估表达式

如果没有使用括号,它将被解释为函数声明,它会导致语法错误,因为函数声明的函数名是可选。

If no parenthesis are used, it will be interpreted as a function declaration, and it will cause a syntax error, since the function name is not optional for function declarations.

(function(arg){
  alert(arg); // alerts test
})("test");

在上面的例子中,函数表达式会自动执行,并传递一个参数。

In the above example, the function expression is automatically executed, passing an argument.

jQuery插件大量使用该模式,因为jQuery可以在 noConflict 模式下运行, $ 全局变量将不会被创建,因此jQuery全局对象作为此匿名函数的参数传递,并且在该函数内部,您可以自由地将其称为 $ (收到的参数)。

That pattern is heavily used by jQuery plugins, since jQuery can run in noConflict mode, the $ global variable will not be created, so the jQuery global object is passed as an argument of this anonymous function and inside of that function, you can freely refer to it as $ (the received argument).

请记住,函数上下文( this 关键字)在像上面例子一样调用的自执行函数表达式中,将始终引用Global对象。

Keep in mind that also, the function context (the this keyword) inside self-executing function expressions invoked like the above example, will refer always to the Global object.

有关函数表达式之间差异的更深入信息和函数声明,看看以下资源:

For a more in-depth info about the differences between function expressions and function declarations, give a look to the following resources:

  • Explain JavaScript’s encapsulated anonymous function syntax
  • Named function expressions demystified

这篇关于关于jquery闭包的一个简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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