9

In the following code, in the object literal for obj1, I would assume that the 'this' in both functions would refer to obj1, but in the fat arrow function, it does not. Can someone explain why? I would have assumed that the functions would either be equivalent or that in the fat arrow function, 'this' would be defined lexically as obj1.

var obj1 = {
  name : 'name1',

  standardFunction : function() {
    console.log(this.name);        //  Refers to obj1
  },

  fatArrowFunction : () => {       //  Refers to the global object
    console.log(this.name);        
  }
}

obj1.standardFunction();
obj1.fatArrowFunction();
Peter Gardner
  • 320
  • 4
  • 9
  • `this` *is* resolved lexically. I.e. it refers to the value of `this` of the environment where `obj1` is defined. And there, `this` doesn't refer to `obj1`. – Felix Kling Aug 30 '17 at 02:19

1 Answers1

5

By definition arrow functions behave differently than the traditional ones. A function defined with () => {} syntax inherits context from the outer scope.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79