【发布时间】:2019-12-12 21:15:37
【问题描述】:
(请各位程序员理解我退伍后正在重新学习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
为什么在最后两条语句中每次调用add_history() 时都不会重复console.log('addition result : ' + result);?
【问题讨论】:
-
因为在第一次执行 add 函数后你会返回 history 函数,并且你将它存储在变量 add_history 中,所以当你调用 add_history 函数时,它基本上会运行你返回的函数(history)并且在那个历史函数中你是不再执行回调
-
@MladenSkrbic 是对的,
add_history变为history -
对;如果你将
add_history声明为一个函数,比如add,你会得到你期望的结果。
标签: javascript node.js closures