Example of different ways to bind instance methods so they persist access to this
One interesting thing to note: The autobindMethod and the constructorBuiltMethod currently transpile to the same output Javascript ([email protected]).
constructorBuiltMethod - Define and attach the method in the constructor
class MyThing {
constructor() {
this.constructorBuiltMethod = () => {
console.log('myOtherMethod called', this.someProp);
}
}
}manualBindMethod - Define the method on the class, but overwrite it with a bound method in the constructor
class MyThing {
constructor() {
this.manualBindMethod = this.manualBindMethod.bind(this);
}
manualBindMethod() {
console.log('manualBindMethod called', this.someProp);
}
}autobindMethod - Define the method on the class as an arrow function, which takes the class this
class MyThing {
autobindMethod = () => {
console.log('myMethod called', this.someProp);
}
}