Created
November 20, 2017 07:20
-
-
Save woosungchu/544b98df85b976ead1174ea1edbb913f to your computer and use it in GitHub Desktop.
Apply vs. Call vs. Bind Examples
This file contains hidden or 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
/* | |
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