Skip to content

Instantly share code, notes, and snippets.

@woosungchu
Created November 20, 2017 07:20
Show Gist options
  • Save woosungchu/544b98df85b976ead1174ea1edbb913f to your computer and use it in GitHub Desktop.
Save woosungchu/544b98df85b976ead1174ea1edbb913f to your computer and use it in GitHub Desktop.
Apply vs. Call vs. Bind Examples
/*
https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind
*/
function call(){
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.call(person1, 'Hello'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King
};
function apply(){
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.apply(person1, ['Hello']); // Hello Jon Kuperman
say.apply(person2, ['Hello']); // Hello Kelly King
}
function bind(){
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say() {
console.log('Hello ' + this.firstName + ' ' + this.lastName);
}
var sayHelloJon = say.bind(person1);
var sayHelloKelly = say.bind(person2);
sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment