是“(function ( ) { } ) ( )”吗?和“(函数(){}())” JavaScript 中功能相同?
这两个代码块都位于alert foo
下面,然后是bar
。唯一的区别是 })()
和 }())
。
代码 1:
(function()
{
bar = 'bar';
alert('foo');
})();
alert(bar);
代码 2:
(function()
{
bar = 'bar';
alert('foo');
}());
alert(bar);
那么,除了语法之外,还有什么区别吗?
Both of these code blocks below alert foo
then bar
. The only difference is })()
and }())
.
Code 1:
(function()
{
bar = 'bar';
alert('foo');
})();
alert(bar);
Code 2:
(function()
{
bar = 'bar';
alert('foo');
}());
alert(bar);
So is there any difference, apart from the syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有什么区别。两者都是函数表达式。
还有第三种方法:(
除了
+
之外,另一个运算符也可以工作)最常见的方法是
while。
There's no difference. Both are function expressions.
There is be a third way, too:
(instead of the
+
another operator would work, too)The most common way is
though.
不;它们是相同的
,但是,如果您事先添加
new
并在之后添加.something
,它们将会不同。代码 1
此代码创建该函数类的新实例,然后获取新实例的
prop
属性。它返回
4
。它相当于
代码 2
此代码调用
Class
属性上的new
。由于函数调用的括号位于外部括号内,因此
new
表达式不会拾取它们,而是正常调用该函数,返回其返回值。new
表达式解析到.Class
并实例化它。 (new
后面的括号是可选的)它相当于
在调用
getNamespace()
时没有括号,这将被解析为(new getNamespace()) .Class
— 它将调用实例化getNamespace
类并返回新实例的Class
属性。No; they are identical
However, if you add
new
beforehand and.something
afterwards, they will be different.Code 1
This code creates a new instance of this function's class, then gets the
prop
property of the new instance.It returns
4
.It's equivalent to
Code 2
This code calls
new
on theClass
property.Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the
new
expression, and instead call the function normally, returning its return value.The
new
expression parses up to the.Class
and instantiates that. (the parentheses afternew
are optional)It's equivalent to
Without the parentheses around the call to
getNamespace()
, this would be parsed as(new getNamespace()).Class
— it would call instantiate thegetNamespace
class and return theClass
property of the new instance.没有什么区别 - 左大括号仅用作语法提示,告诉解析器后面是一个函数表达式,而不是函数声明。
There's no difference - the opening brace only serves as a syntactic hint to tell the parser that what follows is a function expression instead of a function declaration.