VL4D
VL4D

Reputation: 11

When a function has a name and when has no name?

When adding a new method to an object through a method the function has no name (anonymous), and when writing a new method for an object in the code, the function has a name. Why does it happen this way?

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

}

Upvotes: 1

Views: 247

Answers (1)

Barmar
Barmar

Reputation: 781004

When the value of a property in an object literal is an anonymous function, the property name is automatically added as the name of the function.

This is done because this is a common way to define object methods, so the property name is automatically used as the name of the method function.

It doesn't happen if the function is defined outside the object literal and later assigned to a property. You could do that yourself in the addMethod() method:

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

Upvotes: 2

Related Questions