是“(function ( ) { } ) ( )"和“(函数(){}())";在 JavaScript 中功能相同? [英] Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript?
问题描述
警报 foo
和 bar
下的这两个代码块.唯一的区别是 })()
和 }())
.
Both of these code blocks below alert foo
then bar
. The only difference is })()
and }())
.
代码 1:
(function()
{
bar = 'bar';
alert('foo');
})();
alert(bar);
代码 2:
(function()
{
bar = 'bar';
alert('foo');
}());
alert(bar);
那么除了语法之外还有什么区别吗?
So is there any difference, apart from the syntax?
推荐答案
否;它们是相同的
然而,如果你先添加new
,然后添加.something
,它们就会有所不同.
However, if you add new
beforehand and .something
afterwards, they will be different.
new (function() {
this.prop = 4;
}) ().prop;
此代码创建此函数类的新实例,然后获取新实例的 prop
属性.
它返回 4
.
This code creates a new instance of this function's class, then gets the prop
property of the new instance.
It returns 4
.
相当于
function MyClass() {
this.prop = 4;
}
new MyClass().prop;
代码 2
new ( function() {
return { Class: function() { } };
}() ).Class;
此代码在 Class
属性上调用 new
.
由于函数调用的括号在外括号组内,它们不会被 new
表达式拾取,而是正常调用函数,返回其返回值.new
表达式解析为 .Class
并实例化它.(new
后面的括号是可选的)
This code calls new
on the Class
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 after new
are optional)
相当于
var namespace = { Class: function() { } };
function getNamespace() { return namespace; }
new ( getNamespace() ).Class;
//Or,
new namespace.Class;
如果调用 getNamespace()
没有括号,这将被解析为 (new getNamespace()).Class
— 它会调用实例化 getNamespace
类并返回新实例的 Class
属性.
Without the parentheses around the call to getNamespace()
, this would be parsed as (new getNamespace()).Class
— it would call instantiate the getNamespace
class and return the Class
property of the new instance.
这篇关于是“(function ( ) { } ) ( )"和“(函数(){}())";在 JavaScript 中功能相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!