【问题标题】:When a function has a name and when has no name?什么时候函数有名字,什么时候没有名字?
【发布时间】:2021-11-12 16:28:21
【问题描述】:

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

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

}

【问题讨论】:

    标签: javascript object methods anonymous-function function-constructor


    【解决方案1】:

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

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

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

      this.addMethod = (operator, method) => {
        this.methods[operator] = method;
        if (!method.name) {
          method.name = operator;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 2012-02-12
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      相关资源
      最近更新 更多