1

通过方法向对象添加新方法时,函数没有名称(匿名),而在代码中为对象编写新方法时,函数有名称。为什么会这样?

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;
  }

}

4

1 回答 1

2

当对象字面量中的属性值是匿名函数时,属性名称会自动添加为name函数的名称。

这样做是因为这是定义对象方法的常用方式,因此属性名称会自动用作方法函数的名称。

如果函数在对象字面量之外定义并随后分配给属性,则不会发生这种情况。您可以在以下addMethod()方法中自己执行此操作:

  this.addMethod = (operator, method) => {
    this.methods[operator] = method;
    if (!method.name) {
      method.name = operator;
    }
  }
于 2021-09-17T21:14:17.277 回答