TS7041
The containing arrow function captures the global value of 'this'.
Broken Code ❌
const myObject = {
name: 'Benny',
myMethod: () => {
return this.name;
},
};Fixed Code ✔️
Using this is not allowed in arrow functions (source) because arrow functions aren't made to work with call, apply and/or bind methods (source). We have to replace our arrow function with an anonymous function declaration to prevent that our this context gets captured:
const myObject = {
name: 'Benny',
myMethod: function () {
return this.name;
},
};Since ECMAScript 2015 (ES6) this can be shortened (Object Literal Property Value Shorthand) to:
const myObject = {
name: 'Benny',
myMethod() {
return this.name;
},
};