[英]How does this callback function example work?
(I ask understanding from fellow programmers that I am re-studying nodeJS after I got out of the army. I am a beginner and question maybe too simple but please help with my understanding of the example code bellow) (请各位程序员理解,我退伍后重新学习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());
I expect the result to be following:我希望结果如下:
addition result : 40
execute callback function: 1 : 20 + 20 = 40
addition result : 40
execute callback function: 2 : 20 + 20 = 40
However, the result says:然而,结果说:
addition result : 40
execute callback function: 1 : 20 + 20 = 40
execute callback function: 2 : 20 + 20 = 40
Why is console.log('addition result : ' + result);
为什么是
console.log('addition result : ' + result);
not repeated each time add_history()
is called from the last two statements?每次从最后两个语句调用
add_history()
都不会重复吗?
Note that you are returning a function from the add function.请注意,您正在从 add 函数返回一个函数。
when this block runs:当这个块运行时:
var add_history = add(20, 20, function(result) {
console.log('addition result : ' + result);
});
The callback gets executed, the addition result : 40
logs to the console, and add_history
becomes a reference to the history
function you have defined in the add
function.回调被执行,
addition result : 40
记录到控制台,并且add_history
成为对您在add
函数中定义的history
函数的引用。
Now, when you call add_history
you are calling a reference to the history
function which has nothing to do with the callback.现在,当您调用
add_history
您正在调用与回调无关的history
函数的引用。 But since history
was created in the scope of add
, you have access to the count
variable defined in that scope.但是由于
history
是在add
范围内创建的,因此您可以访问在该范围内定义的count
变量。
You could call your callback by defining the history
function inside the add
function like this:您可以通过在
add
函数中定义history
函数来调用回调,如下所示:
var history = function() {
callback(result)
count += 1;
return count + ' : ' + a + ' + ' + b + ' = ' + result;
}
This would cause the callback to run each time you call add_history
.这将导致每次调用
add_history
时运行回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.