Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' in arrow functions vs non arrow functions in an object literal [duplicate]

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();
like image 295
Peter Gardner Avatar asked Aug 29 '17 19:08

Peter Gardner


1 Answers

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

like image 71
Danil Speransky Avatar answered Sep 22 '22 04:09

Danil Speransky