这个“(function(){});”(括号内的函数)在 JavaScript 中意味着什么?
可能的重复:
这是什么意思? (函数(x,y)){…}){a,b);在 JavaScript 中
JavaScript 对象/函数/ 周围的括号有何作用类声明是什么意思?
大家好,
我不知道以下内容是什么:
(function(){
// Do something here
...
})(someWord) //Why is this here?;
我的问题是:
- 将函数放在括号内的含义是什么。即
(function(){});
? - 函数末尾的括号有什么作用?
我通常在 jquery 代码和其他一些 javascript 库中看到这些。
Possible Duplicates:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
What do parentheses surrounding a JavaScript object/function/class declaration mean?
Hi All
I don't know what the following does:
(function(){
// Do something here
...
})(someWord) //Why is this here?;
My questions are:
- What's the meaning of putting a function inside brackets .i.e.
(function(){});
? - What do the set of brackets do at the end of a function?
I usually see these in jquery codes, and some other javascript libraries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您将立即使用特定参数调用匿名函数。
示例:
这会提醒“peter”。
对于 jQuery,您可以将
jQuery
作为参数传递,并在函数中使用$
。因此,您仍然可以在 noConflict 模式下使用 jQuery,但使用方便的$
:You're immediately calling an anonymus function with a specific parameter.
An example:
This alerts "peter".
In the case of jQuery you might pass
jQuery
as a parameter and use$
in your function. So you can still use jQuery in noConflict-mode but use the handy$
:您正在创建一个立即被调用的函数,并以
someWord
作为参数。You are making a function that is immediately being called, with
someWord
as a parameter.这是一种定义匿名函数然后立即执行它的方法——可以说不留下任何痕迹。该函数的作用域确实是本地的。末尾的
()
括号执行该函数——括弧是为了消除正在执行的内容的歧义。It's a way to define an anonymous function and then immediately executing it -- leaving no trace, as it were. The function's scope is truly local. The
()
brackets at the end execute the function -- the enclosing brackets are to disambiguate what is being executed.基本上,这可以让您声明一个匿名函数,然后将其括在括号中并编写
(someWord)
您就可以运行该函数。您可以将其视为声明一个对象,然后立即实例化该对象。Basically this lets you declare an anonymous function, and then by enclosing it in parentheses and writing
(someWord)
you are running the function. You could think of it as declaring an object and then immediately instantiating the object.它用于创建匿名函数(没有名称的函数,可以“嵌套”在其他函数中)并将参数传递给该函数。
someWord 作为参数传递,函数可以使用关键字“arguments”读取它。
简单的使用示例:
It's used to create anonymous function (function without name that can be "nested" inside other function) and pass argument to that function.
The someWord is passed as argument, and the function can read it using the keyword "arguments".
Simple example of usage: