Created
November 13, 2016 13:00
-
-
Save smks/61c3670be194db869b97edc0e89fbd82 to your computer and use it in GitHub Desktop.
Demonstration of how bind() works in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Incorrect Context | |
* | |
*/ | |
class Greeter { | |
constructor(name) { | |
this.name = name; | |
} | |
greet(event) { | |
console.log('Hello ' + this.name); // undefined | |
} | |
} | |
const greeter = new Greeter('Shaun'); | |
var a = document.createElement('button'); | |
a.id = 'greet-button'; | |
a.innerHTML = 'Say Hello'; | |
a.onclick = greeter.greet; | |
document.body.appendChild(a); | |
/** | |
* | |
* Correct Context | |
* | |
*/ | |
class Greeter { | |
constructor(name) { | |
this.name = name; | |
this.greet = this.greet.bind(this); | |
} | |
greet(event) { | |
console.log('Hello ' + this.name); // 'Shaun' | |
} | |
} | |
const greeter = new Greeter('Shaun'); | |
var a = document.createElement('button'); | |
a.id = 'greet-button'; | |
a.innerHTML = 'Say Hello'; | |
a.onclick = greeter.greet; | |
document.body.appendChild(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment