(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)
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);
not repeated each time add_history()
is called from the last two statements?
Note that you are returning a function from the add function.
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.
Now, when you call add_history
you are calling a reference to the history
function which has nothing to do with the callback. But since history
was created in the scope of add
, you have access to the count
variable defined in that scope.
You could call your callback by defining the history
function inside the add
function like this:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.