简体   繁体   English

JS中的以下定义方式有什么区别?

[英]What's the difference between the following ways of definition in JS?

code block 1: 代码块1:

var a = (function(){
    var obj = {a:'1',b:'2'};
    return obj;
})();
console.log(a);  

code block 2: 代码块2:

var a = function(){
    var obj = {a:'1',b:'2'};
    return obj;
}();
console.log(a);  

I know the results of console.log are the same.But is there any difference during the execution procedure? 我知道console.log的结果是一样的。但是在执行过程中有什么区别吗?

The only effect that putting parenthesis around a function has is to ensure it is treated as a function expression. 将括号括在函数周围的唯一效果是确保将其视为函数表达式。

Putting it as the RHS of an assignment also has that effect. 将其作为任务的RHS也具有这种效果。

Consequently, there is no difference between the two. 因此,两者之间没有区别。

var a = (function(){
    var obj = {a:'1',b:'2'};
    return obj;
})();
console.log(a);  

The function is an IIFE (Immediately invoked function expression). 该函数是IIFE(立即调用的函数表达式)。

The function will be invoked and the returned value will be assigned to a . 将调用该函数,并将返回的值分配给a

In the second expression, Only the syntax differs, but the functionality is same. 在第二个表达式中,只有语法不同,但功能相同。 But as a good practice, it's good to wrap the function within () . 但作为一种好的做法,将函数包装在()是很好的。 If you use just below code, it will give error. 如果你只使用下面的代码,它将给出错误。

function(){
    var obj = {a:'1',b:'2'};
    return obj;
}();

Whereas

(function(){
        var obj = {a:'1',b:'2'};
        return obj;
    }());

and

(function(){
        var obj = {a:'1',b:'2'};
        return obj;
    })();

both won't give error, because we are explicitly defining it to be treated as a expression. 两者都不会给出错误,因为我们明确地将其定义为表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM