gpt4 book ai didi

javascript - 这个回调函数示例如何工作?

转载 作者:行者123 更新时间:2023-11-29 22:51:48 24 4
gpt4 key购买 nike

(请各位程序员谅解,我退伍后正在重新学习nodeJS,我是初学者,问题可能太简单了,请帮助我理解下面的示例代码)

function add(a, b, callback) {
var result = a + b;
callback(result);
var count = 0;

var history = function() {
count += 1;
return count + ' : ' + a + ' + ' + b + ' = ' + result;
};
return history;

}

var add_history = add(20, 20, function(result) {
console.log('addition result : ' + result);
});


console.log('execute callback function: ' + add_history());
console.log('execute callback function: ' + add_history());

我希望结果如下:

addition result : 40
execute callback function: 1 : 20 + 20 = 40
addition result : 40
execute callback function: 2 : 20 + 20 = 40

但是,结果显示:

addition result : 40
execute callback function: 1 : 20 + 20 = 40
execute callback function: 2 : 20 + 20 = 40

为什么 console.log('addition result : ' + result); 每次从最后两个语句调用 add_history() 时都不重复?

最佳答案

请注意,您正在从 add 函数返回一个函数。

当这个 block 运行时:

var add_history = add(20, 20, function(result) {
console.log('addition result : ' + result);
});

回调被执行,addition result : 40 记录到控制台,并且 add_history 成为对 history 的引用您在 add 函数中定义的函数

现在,当您调用 add_history 时,您调用的是对 history 函数的引用,它与回调无关。但是由于 history 是在 add 范围内创建的,您可以访问在该范围内定义的 count 变量。

您可以通过在 add 函数中定义 history 函数来调用回调,如下所示:

var history = function() {
callback(result)
count += 1;
return count + ' : ' + a + ' + ' + b + ' = ' + result;
}

这会导致回调在您每次调用 add_history 时运行。

关于javascript - 这个回调函数示例如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com