adamhl.dev

JavaScript Arrow Function 'this' Binding

1 min read


JS Arrow Function ‘this’ Binding

Arrow functions create a permanent link to the surrounding lexical scope through a mechanism called “lexical this”.

  • They form a closure over the current scope, including the value of this.

Example:

class Example {
constructor() {
this.value = 42
}
regularMethod() {
console.log(this.value) // 'this' depends on how it's called
}
arrowMethod = () => {
console.log(this.value) // 'this' is always the instance of Example
}
}
const ex = new Example()
const regular = ex.regularMethod
const arrow = ex.arrowMethod
regular() // undefined (or throws error in strict mode)
arrow() // 42