Skip to content

Instantly share code, notes, and snippets.

@AdamJonsson
Last active February 8, 2020 14:22
Show Gist options
  • Save AdamJonsson/9313cf753d6ecab5e83a00394def41df to your computer and use it in GitHub Desktop.
Save AdamJonsson/9313cf753d6ecab5e83a00394def41df to your computer and use it in GitHub Desktop.
A example how binding works in JS
// Look at the following class
class Suprise {
constructor(name, age) {
this.name = name;
this.age = age;
setTimeout(this.alertSuprise, 1000);
}
alertSuprise() {
alert(`Happy birthday ${this.name}! You are now ${this.age} years old`);
}
}
// Why do the following do not print the suprise alert correctly after one secound?
// What can be done to fix this?
new Suprise('Adam', 20);
// The answer is that "this" referes to the inside of the setTimeout function
// where it is called. The result is that this.name and this.age do not exist
// in that scope.
// One solution is to bind "this" to the alertSuprise function
setTimeout(this.alertSuprise, 1000); // OLD
setTimeout(this.alertSuprise.bind(this), 1000); // NEW
// Then "this" is going to refer correctly to the Suprise object when it is called.
// Another solution is to take use of closuers by creating a new function that calls alertSuprise
setTimeout(this.alertSuprise, 1000); // OLD
setTimeout(() => this.alertSuprise(), 1000); // NEW
// Because "this" refers to the Suprise object when the function was created, "this" inside the alert function
// is also going to refer to the suprise object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment