这段 JavaScript 代码是什么意思?
var myval = (function(){})();
我不明白 (function..)
的含义,甚至不理解其他代码。
var myval = (function(){})();
I don't understand (function..)
meaning and even else code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您所得到的是:
自调用匿名函数
您首先通过在函数本身周围添加括号来创建函数表达式。
在这种情况下,仅仅编写
是行不通的,因为这将定义一个函数声明。
因此,在我们完成之后,我们可以通过附加
()
来调用自身。要验证这一点,请尝试以下操作:
What you've got there is a:
self-invoking anonymous function
You're first creating a function-expression by having paranthesis around the function itself.
Just to write
would not work in this instance, because this would define a function-declaration.
So after we have that, we can call itself by appending
()
To verify that, try this:
function(){}
— 是一个函数表达式,它定义了一个函数(function(){})
— 像这样包装它可以确保它被视为一个表达式()
调用函数,然后将返回值分配给变量。
这通常用于允许使用变量而不污染全局范围。
function(){}
— is a function expression, it defines a function(function(){})
— wrapping it like this makes sure it gets treated as an expression(function(){})()
— Adding()
calls the functionAnd then the return value is assigned to a variable.
This is usually used to allow variables to be used without polluting the global scope.
这将创建一个匿名函数并立即调用它。例如,
将允许您在其中使用
$
,它等于jQuery
。This creates an anonymous function and immediately calls it. For example
will allow you to use
$
in there and it equalsjQuery
.此
function(){}
定义了没有函数体的匿名函数(closure)。通过将其括在大括号中并在末尾添加空参数列表 (()
),您将运行此闭包。这本质上相当于:这会更容易理解吗?
This
function(){}
defines anonymous function(closure)with no body. By wrapping it in braces and adding empty parameters list at the end (()
) you are running this closure. This is essentially equivalent to:Would this be easier to grasp?
相关链接:
Related links:
我们来逐条分析一下:
这里定义了一个匿名函数(即没有名字的函数)
当然如果在
{}
括号之间放一些指令会更有用。现在,如果您将
函数分配给 myval(函数,而不是其返回值!)
,那么您可以调用 myval() ,这与调用函数本身相同。
在这里,您可以通过在末尾放置
()
来调用该函数。因此:调用该函数,并将结果(这次不是函数本身)放入
myval
Let's analyze it piece by piece:
This define an anonymous function (i.e. a function with no name)
Of course it would be more useful to put some instruction in between the
{}
brackets.Now if you did
You assign the function to myval (the function, NOT its return value!)
So then you could call
myval()
and it would be the same as calling the function itself.Here instead you do call the function by putting
()
at the end. Therefore:calls the function, and puts the result (not the function itself this time) in
myval