0

Can't find this info anywhere on the web. Is there any difference (e.g. in performance) between these two methods created with object literal syntax? Or is the mechanism under the hood exactly the same?

let test = {

  foo(){
    console.log("foo");
    return 1;
  },
  bar: () => {
    console.log("bar");
    }
}


console.log(test.foo());
console.log(test.bar());
Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
  • 2
    Yes; `this` will be different. – SLaks Mar 08 '18 at 21:49
  • 2
    `foo` returns a value of `1`, `bar` returns `undefined` – Jaromanda X Mar 08 '18 at 21:52
  • To elaborate on Slaks comment above... `this` will be bound to the lexical scope of `test` with an arrow function, whereas `this` will be `undefined` in `foo`. Take a look at [the MDN docs on arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Arrow_functions) – Chad Lewis Mar 08 '18 at 21:59

1 Answers1

1

There shouldn't be any performance difference -- the shorthand function property is just syntactic sugar.

However, there's an operational difference. The shorthand notation is short for the traditional function syntax, not an arrow function. So it's equivalent to:

foo: function() {
    console.log("foo");
}

Arrow functions have a number of different behaviors from traditional function expressions. See Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

Your example functions don't do anything that depends on the differences, but in a real application they might.

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • I would've thought `bar:() => { console.log("bar"); }` was equivalent to `bar: function() { console.log("bar"); }.bind(this)` (where `this` would NOT be `test` as it is in `foo`) – Jaromanda X Mar 08 '18 at 21:55
  • @JaromandaX That's the main difference, but there are others. – Barmar Mar 08 '18 at 21:57