The Daily TIL

February 18, 2019 by AndyAndyjavascript

Arrow functions don't really have a `this`

An arrow function does not have its own this. When you use this in an arrow function, the this value of the enclosing lexical scope is used.

Because of this difference between arrow functions and function functions, arrow functions are best suited for non-method functions (functions that are not part of a class).

Example

As stated previously, arrow function expressions are best suited for non-method functions. Let’s see what happens when we try to use them as methods:

var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log(this.i, this);
  }
}


obj.b(); // prints undefined, Window {...} (or the global object, which is the closest enclosing scope). If you're in Node, this will probably be the current module.

obj.c(); // prints 10, Object {...}

References