javascript 中的闭包是什么意思?

what's the meaning of the closures in javascript?

参考自网络

它说它可以像这样从外部访问函数内部值:

function a(){           
    var scope = "local scope";
    function f(){return scope;}    
    return f; 
} 
console.log(a()());//it can get the value 'local scope'

我的问题是这段代码有什么不同

function a(){           
    var scope = "local scope"; 
    return scope; 
} 
console.log(a());//it can get the value 'local scope' too

那么闭包的含义是什么?

为什么需要将 return 值换行 function

什么是闭包,请阅读这一篇,最好的解释
JavaScript closures vs. anonymous functions

function a(){           
    var scope = "local scope"; 
    return scope; 
} 
console.log(a());

在这种情况下你只能return局部变量你不能对变量应用任何操作如果你需要任何

function a(){           
    var scope = "local scope";
    function f(b){return scope + b;}    
    return f; 
} 
console.log(a()('found here'));
console.log(a()(' not found here'));

但在这种情况下,您可以根据需要操作该数据。

我的意思是说我们可能需要关闭。

这里是闭包的一种可能用法:

var getUid = function () {
    var uid = 1;
    return function () {
        return uid++;
    };
};

// invoke the wrapping function immediately
// to create a single local scope
getUid = getUid();

getUid(); // 1
getUid(); // 2
getUid(); // 3

如您所见,闭包允许在函数调用之间保留 "uid" 局部变量 "alive"。它的值保留在内存中,它是持久化的,不像没有内部函数的时候:

var getUid = function () {
    var uid = 1;
    return uid++;
};

getUid(); // 1
getUid(); // 1
getUid(); // 1

总而言之,关于闭包的有趣之处在于能够使局部变量持久化。

在您的示例中,有一些值得注意的地方。注意写a()()和写(a())()是一样的。这意味着您首先调用包装函数 "a", 创建一个新范围 ,因此,"a" 中的所有内容都被完全重新创建。

如果您继续以这种方式创建新范围,则没有理由使用闭包。事实上,这样做你失去了在函数调用之间保持变量活动的能力(如上所述)。让我们看看如果这样使用 getUid() 会发生什么:

var getUid = function () {
    var uid = 1;
    return function () {
        return uid++;
    };
};

getUid()(); // 1
getUid()(); // 1
getUid()(); // 1

与没有内部函数一样的结果。不是很有用吧?但是,如果您需要创建多个范围,您仍然可以利用重复调用包装函数,但是您必须将内部函数存储到变量中:

var getUidA = getUid(); // scope A
var getUidB = getUid(); // scope B

getUidA(); // A 1
getUidA(); // A 2
getUidB(); // B 1
getUidA(); // A 3
getUidB(); // B 2

我不确定关于闭包的基本原理还有很多要说的,其他程序员会判断。无论如何,如果您准备好头痛,您可能会对内存中低级别发生的事情感兴趣:.