This is a spiritual sequel to this article.
Create a class with a method using Traditional function like so. Let’s call this Approach A.
// APPROACH A
class SomeClass {
constructor() {
this.someProp = 'someValue';
}
someMethod() { // Traditional function
console.log(this.someProp);
}
}
Create an instance of that class. When invoking the method on the instance, this
refers to the instance. So far, it’s behaving as expected.
let instance = new SomeClass();
instance.someMethod(); // logs 'someValue'
But, as soon as we assign the method to a variable and call that function variable, the method loses its context, and you get Uncaught TypeError: Cannot read property ‘someProp’ of undefined.
let instance = new SomeClass();
let funcVariable = instance.someMethod;
funcVariable(); // logs error
#javascript #coding #web-development #react