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();
By definition arrow functions behave differently than the traditional ones. A function defined with () => {}
syntax inherits context from the outer scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With