我正在阅读一些教程并看到了我无法弄清楚的代码块。有人可以带我走过吗?我不明白返回最终如何执行变量函数。
var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };
var operations = {
'+': plus,
'-': minus
};
var calculate = function(x, y, operation){
return operations[operation](x, y);
}
calculate(38, 4, '+');
calculate(47, 3, '-');
答案 0 :(得分:3)
操作是一个具有+和 - 作为键的对象,因此通过将其中一个传递给它,您将获得
operations['+'] = plus
现在,括号表示函数调用,也可以通过变量进行,如本例所示。所以翻译的return语句只不过是
return plus(x,y);
var calculate = function(x, y, operation){
return operations[operation](x, y); // operations['+'] = plus
}
调用上面的方法并返回该方法返回的值。
答案 1 :(得分:2)
执行将是这样的:
第一个参数作为对象的键传递,各个函数用参数执行..
var calculate=function(x, y, operation)
{
//operations['+'](38, 4);
//operations['-'](47, 3);
return operations[operation](x, y);
};
答案 2 :(得分:2)
请查看我的评论以获得解释。
var plus = function(x,y){ return x + y }; //-- var plus contains this function now.
var minus = function(x,y){ return x - y };
var operations = {
'+': plus, //-- This states that '+' contains the plus function.
'-': minus //-- This states that '-' contains the minus function.
};
var calculate = function(x, y, operation){ //-- operation makes it able to select a function from operations.
return operations[operation](x, y);
}
calculate(38, 4, '+'); //-- The '+' selects the plus function here.
calculate(47, 3, '-'); //-- The '-' selects the minus function here.