不完全正确。 闭包在内部函数被定义时就已经被创建了,而不是等到内部函数返回值时才被创建。 以下是一个简单的示例来说明这一点:
function createClosure() {
var outerVariable = "hello";
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
var closure = createClosure();
closure(); // 输出 "hello"
在这个例子中,当createClosure
被调用时,它返回一个内部函数innerFunction
,该内部函数引用了outerVariable
,因此outerVariable
被包含在闭包中。当createClosure
返回后,闭包依然存在,并仍然可以访问outerVariable
,因此当closure()
被调用时,"hello"被输出。
因此,即使内部函数没有返回任何值,闭包也会被创建。
下一篇:闭包值在没有重置的情况下发生变化