需要一些有关以以下样式声明变量的信息

need some info on declaring the variable in the following style

本文关键字:声明 样式 变量 信息      更新时间:2023-09-26

可能的重复项:
JavaScript 范围和闭包
JavaScript - 自执行函数

以下代码有什么区别:


var someVar = (function(){
   // some code
})();


var someVar = function(){
   // some code
};

你能给我指出关于第一个代码的使用和解释的教程吗?

在谷歌上很难找到答案,所以我想我会在这里问它。

谢谢。

第一种情况

将被创建并执行匿名函数。函数结果将存储在someVar中。

var someVar = (function(){
    console.log('function executed');
    return 1;
})();
// function executed
console.log(someVar);
// 1

第二种情况

创建匿名函数,其引用将存储在someVar中。

var someVar = function(){
    console.log('function executed');
    return 1;
};
var result = someVar();
// function executed
console.log(result);
// 1