Skip to content

Instantly share code, notes, and snippets.

@smks
Created November 13, 2016 13:00
Show Gist options
  • Save smks/61c3670be194db869b97edc0e89fbd82 to your computer and use it in GitHub Desktop.
Save smks/61c3670be194db869b97edc0e89fbd82 to your computer and use it in GitHub Desktop.
Demonstration of how bind() works in JavaScript
/**
*
* 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