Passing An Anonymous Function As A Parameter With Preset Parameter Values
I ran into this by accident and am not sure how my 'popAndGo' function is working. function Calculator(){ var stack = []; var popAndGo = function(performer){ var firstPop
Solution 1:
Maybe you will visualize it better this way:
var popAndGo = function(){
var performer = function(first, second){
return first + second;
};
var firstPop = stack.pop();
var secondPop = stack.pop();
var result = performer(firstPop, secondPop);
stack.push(result);
};
Or, simplifying,
var popAndGo = function(){
var firstPop = stack.pop();
var secondPop = stack.pop();
var result = firstPop + secondPop;
stack.push(result);
};
Solution 2:
this.plus = function(){
popAndGo(function(first, second){
return first + second;
});
};
The function that you pass as the argument to popAndGo
is an anonymous function with two parameters. That anonymous function gets bound to the parameter performer
in popAndGo
.
When calling performer
with the values of firstPop
and secondPop
these get bound to the parameters first
and second
in the anonymous function. The anonymous function's body gets executed returning the sum of the arguments.
Post a Comment for "Passing An Anonymous Function As A Parameter With Preset Parameter Values"