【问题标题】:How does this callback function example work?这个回调函数示例是如何工作的?
【发布时间】: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


【解决方案1】:

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

当这个块运行时:

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

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多