"this" in Arrow Function
suggest changeFor a regular function, this is determined by how the function is called. An arrow function captures this from the surrounding lexical scope.
The diagram below shows the same distinction.
The same distinction in code:
const service = {
name: 'mailer',
regularMethod() {
console.log(this.name);
},
methodWithArrow() {
const nested = () => console.log(this.name);
nested();
},
};
service.regularMethod();
service.methodWithArrow();
mailer
mailer
regularMethod receives service as this because it is called through service. The nested arrow retains that same value. Avoid relying on top-level this, because its value differs between CommonJS modules and ECMAScript modules.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents