是“(function(){})()”和“(function(){}())”在JavaScript中功能相同? [英] Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript?

查看:109
本文介绍了是“(function(){})()”和“(function(){}())”在JavaScript中功能相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的这两个代码块警告 foo 然后 bar 。唯一的区别是})()}())



代码1:

 (function()
{
bar ='bar' ;
alert('foo');
})();

alert(bar);

代码2:

 (function()
{
bar ='bar';
alert('foo');
}());

alert(bar);

所以除了语法之外,还有什么区别?

解决方案

不;它们是相同的




但是,如果您事先添加 new .something 之后,它们会有所不同。



代码1



  new(function(){
this.prop = 4;
})().prop;

此代码创建此函数类的新实例,然后获取 prop 新实例的属性。

它返回 4



它相当于

 函数MyClass(){
this.prop = 4;
}
new MyClass()。prop;






代码2



  new(function(){
return {Class:function(){}};
}()).Class;

这段代码在<$ $上调用 new c $ c> Class 属性。

由于函数调用的圆括号位于外部圆括号内,所以它们不会被新的表达式,而是通常调用函数,返回它的返回值。

new 表达式解析为 .Class 并实例化。 ( new 之后的括号是可选的)



它相当于

  var namespace = {Class:function(){}}; 

函数getNamespace(){return namespace; }

new(getNamespace()).Class;
//或者,
new namespace.Class;

如果调用 getNamespace(),这将被解析为(new getNamespace())。Class —它会调用实例化 getNamespace 类并返回新实例的 Class 属性。


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?

解决方案

No; they are identical


However, if you add new beforehand and .something afterwards, they will be different.

Code 1

new (function() {
    this.prop = 4;
}) ().prop;

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

function MyClass() {
    this.prop = 4;
}
new MyClass().prop;


Code 2

new ( function() {
    return { Class: function() { } }; 
}() ).Class;

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)

It's equivalent to

var namespace = { Class: function() { } };

function getNamespace() { return namespace; }

new ( getNamespace() ).Class;
//Or,
new namespace.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(){})()”和“(function(){}())”在JavaScript中功能相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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