我正在用JS "Closures"讨论这个主题,并试图对这个概念做一些实验。我创建了两个函数并检查那里的输出



both function打印"outer"one_answers";inner"函数两次。

使用简单的函数声明&执行

function outer1() {
var j = 20;
function inner1() {
var k = 30;
console.log(j, k);
j++;
k++;
}
inner1(); //calling inner1 
return;
}
outer1(); // calling function 2 times
outer1();

output : // same output both time
20 30
20 30

//-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x

使用函数表达式

function outer() {
var a = 20;
var inner = function() {
var b = 30;
console.log(a, b);
a++;
b++;
}
return inner; //returning inner
}
var func = outer();
func(); // calling function 2 times
func();

output : // value of a is incremented by 1 time.
20 30
21 30

我很困惑,为什么两者都显示不同的结果第一个但第二个不一样?

在第一个示例中,您多次运行outer()。这样每次都会创建一个新的内部函数,每个函数的初始值都是j

如果你熟悉类,这有点像调用new Thing().do(); new Thing().do();const thing = new Thing(); thing.do(); thing.do();

最新更新