我偶然遇到了这个问题,不确定我的'popAndGo'函数是如何工作的。将匿名函数作为参数传递给预设的参数值
function Calculator(){
var stack = [];
var popAndGo = function(performer){
var firstPop = stack.pop();
var secondPop = stack.pop();
var result = performer(firstPop, secondPop);
stack.push(result);
};
this.push = function(num){
stack.push(num);
};
this.value = function(){
return stack[stack.length -1];
};
this.plus = function(){
popAndGo(function(first, second){
return first + second;
});
};
}
我正在练习让我的代码遵循DRY实践,并创建了这个popAndGo函数。它采用一个匿名函数,并在收集两个参数(检查加号函数)后调用该函数。
我不确定这些参数是如何工作的。我通常理解参数,它们基本上是您最终通过函数的实际参数的占位符。
但是在this.plus的情况下,我传递了一个具有两个参数的匿名函数。他们如何代替表演者(firstPop,secondPop)?我想象它的工作原理如下:
var popAndGo = function(performer){
var firstPop = stack.pop();
var secondPop = stack.pop();
var result = performer(firstPop, secondPop);
stack.push(result);
};
this.plus = function(){
popAndGo(function(first, second){
return first + second;
});
};
}
// CHECK the parameters on this popAndGo, this is how I picture this working.
var popAndGo = function(function(first, second){
var firstPop = stack.pop();
var secondPop = stack.pop();
var result = function(first, second);
stack.push(result);
};
这些值不匹配。如果任何人都可以解释如何将这个函数传入我的popAndGo函数并且与这些值相匹配,那么它会清除我所遇到的很多混乱,谢谢!
测试用例我写这个代码:
// See http://en.wikipedia.org/wiki/Reverse_Polish_notation
describe("Calculator using reverse polish notation", function() {
var calculator;
beforeEach(function(){
calculator = new Calculator();
});
it("adds two numbers", function() {
calculator.push(2);
calculator.push(3);
calculator.plus();
expect(calculator.value()).toEqual(5);
});
it("adds three numbers", function() {
calculator.push(2);
calculator.push(3);
calculator.push(4);
calculator.plus();
expect(calculator.value()).toEqual(7);
calculator.plus();
expect(calculator.value()).toEqual(9);
});
}
有更多的测试和更多的功能,我不得不为它编写。在每一个函数中,我都从堆栈中弹出两个值,然后再推回总值。我想写一个功能,我这样做,所以我没有不断重复自己。
你能告诉我们你想怎么用'Calculator'的实例进行交互? – naomik
当然,让我发布我正在编写的代码传递的测试。 – HelloWorld
我不明白你在问什么,但是如果你想知道'first'和'second'从哪里得到它们的值,那是因为你正在向函数传递值:'performer(firstPop,secondPop)'。 –