-1

I wish to know how to implement an arrow function inside a case statement. Please what is the way to obtain for example 15 into 'result' if I do something similar?

var result = num.calculate('+');

var num = {
  x: 12,
  y: 3,
  calculate: function(operation) {
    var fn;
    switch (operation) {
      case '+':
        fn = function() {
          return this.x + this.y
        };
        break;
      case '-':
        fn = function() {
          return this.x - this.y
        };
        break;
      default:
        fn = function() {};
    }
    return fn();
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `function() { return this.x + this.y};` becomes `() => { return this.x + this.y}` or `() => this.x + this.y` – VLAZ Apr 23 '20 at 09:58
  • I made you a snippet. Please make a [mcve] with input and expected output – mplungjan Apr 23 '20 at 09:59
  • I'm not convinced the dupe is accurate. It seems it's not about `calculate` being an arrow function but `calculate` having arrow functions inside it. – VLAZ Apr 23 '20 at 10:00
  • The problem is that he can't access the `x` and `y` in those functions. That dupe covers that. – Cerbrus Apr 23 '20 at 10:11

1 Answers1

0

The x and y properties exist on the calling context, the num object - either reference num.x, or when calling the function, use fn.call(num) so that the this inside the function refers to the num object:

var num = {
  x: 12,
  y: 3,
  calculate: function(operation) {
    var fn;
    switch (operation) {
      case '+':
        fn = function() {
          return this.x + this.y
        };
        break;
      case '-':
        fn = function() {
          return this.x - this.y
        };
        break;
      default:
        fn = function() {};
    }
    return fn.call(num);
  }
}



risult = num.calculate('+');
console.log(risult);

You could also use arrow functions, so that the this is inherited from the outer scope instead, eg fn = () => this.x + this.y:

var num = {
  x: 12,
  y: 3,
  calculate: function(operation) {
    var fn;
    switch (operation) {
      case '+':
        fn = () => this.x + this.y
        break;
      case '-':
        fn = () => this.x - this.y;
        break;
      default:
        fn = function() {};
    }
    return fn();
  }
}



risult = num.calculate('+');
console.log(risult);

But switch is quite verbose and can be pretty error-prone. How about using an object indexed by operation instead (and use correct spelling to prevent bugs, use result, not risult):

const fns = {
  '+': () => num.x + num.y,
  '-': () => num.x - num.y,
};
var num = {
  x: 12,
  y: 3,
  calculate: operation => {
    const fn = fns[operation] || (() => null);
    return fn();
  }
};
const result = num.calculate('+');
console.log(result);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320