这是什么? (function(){})() [英] What is this? (function(){ })()

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

问题描述


可能存在重复:

这段JavaScript代码片段是什么意思?

自动执行匿名JavaScript函数括号的位置?






 (function(){

//在这里的东西...

})()< - //这部分就在这里。

究竟是什么)()

如果我将它改为())

 (function(){

// something here ...
$ b $())< - //像这样


解决方案

这声明了一个匿名函数并立即调用它。
$ b

这样做的好处是函数内部使用的变量不会被添加到当前范围中,而且您也不会将函数名称添加到当前范围中。 b
$ b

请注意,函数声明周围的括号不是任意的。最后,您可以使用额外的圆括号将参数实际传递给匿名函数,如

$ b中的
$ b

 (function(arg){
//用arg $ b $做一些事情))(1);

请参阅 http://jsfiddle.net/eb4d4/


Possible Duplicates:
What does this JavaScript snippet mean?
Location of parenthesis for auto-executing anonymous JavaScript functions?

(function(){

    //something here...

})() <--//This part right here.

What exactly is this )()?
What if I change it to this ())?

(function(){

    //something here...

}()) <--//Like this

解决方案

This declares an anonymous function and calls it immediately.

The upside of doing this is that the variables the function uses internally are not added to the current scope, and you are also not adding a function name to the current scope either.

It is important to note that the parentheses surrounding the function declaration are not arbitrary. If you remove these, you will get an error.

Finally, you can actually pass arguments to the anonymous function using the extra parentheses, as in

(function (arg) {
   //do something with arg
})(1);

See http://jsfiddle.net/eb4d4/

这篇关于这是什么? (function(){})()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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