"this" in Arrow Function

suggest change

For 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents