通过方法向对象添加新方法时,函数没有名称(匿名),而在代码中为对象编写新方法时,函数有名称。为什么会这样?
let calc = new Calculator;
//console.log( calc.calculate("3 + 7") );
let powerCalc = new Calculator;
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);
let result = powerCalc.calculate("2 ** 3");
//console.log( result );
console.log(powerCalc.methods["+"].name); // has a name
console.log(powerCalc.methods["*"].name); // has no name
function Calculator () {
this.methods = {
"-": (a, b) => a - b,
"+": (a, b) => a + b,
};
this.calculate = (str) => {
let split = str.split(" "),
a = Number(split[0]),
operator = split[1],
b = Number(split[split.length-1]);
if (!this.methods[operator] || isNaN(a) || isNaN(b)) return NaN;
return this.methods[operator](a, b);
}
this.addMethod = (operator, method) => {
this.methods[operator] = method;
}
}