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.regularMethodconst arrow = ex.arrowMethod
regular() // undefined (or throws error in strict mode)arrow() // 42regularMethodloses itsthiscontext when assigned to a variable.arrowMethodretains itsthiscontext because it was bound to the instance when the arrow function was created.