Let’s see this in actual examples.
class Cat {
name;
constructor(name) { this.name = name; }
getName() {
return this.name; // "this" can refer to other objects when rebinded.
}
getNameArrow = () => {
return this.name; // "this" will always refer to the original object.
}
}
let me show what does rebinding mean:
const tigger = new Cat("Tigger");
const charlie = new Cat("Charlie");
then let’s swap their methods:
charlie.getName = tigger.getName;
tigger.getNameArrow = charlie.getNameArrow;
Now Charlie is using the normal method(function) from Tigger, while Tigger is using the arrow function from Charlie.
let’s see what will happen if we get their name:
charlie.getName();
// Charlie
tigger.getNameArrow();
// Charlie
So what is going on here? Since “this
” reference in arrow functions will always refer to the “this” on its creation, even it is being assigned to other objects, it will still refer to the original object it belongs to.
In contrast, normal methods(which actually are functions) can be reassigned to other objects and the “this” reference will refer to the new owner. Search “javascript function binding” can give you more information.