Skip to content

Instantly share code, notes, and snippets.

@topicus
Created March 20, 2017 20:05
Show Gist options
  • Save topicus/adcad2acbbcf8573f804b04fcc4da110 to your computer and use it in GitHub Desktop.
Save topicus/adcad2acbbcf8573f804b04fcc4da110 to your computer and use it in GitHub Desktop.
How bind, call and apply change the this.
function printName(id) {
console.log(this.name + id);
}
let person = {
name: 'Person Marian'
};
let human = {
name: 'Human Charles'
}
// Create a new function and bind printPersonName to person
let printPersonName = printName.bind(person);
// Create a new function and bind printHumanName to human
// This doesn't work because printPersonName was already bind and
// you can't change where this points to except during execution
// by using call and apply.
let printHumanName = printPersonName.bind(human);
// Change this using call or apply
// Call print name but replace this with person.
// You can read this like send the message printName
// to the object person.
printName.call(person, 1); // Output: "Person Marian1"
printName.call(human, 1); // Output: "Human Charles1"
// Similar to call but second argument is the array of arguments
// to be passed to the printName function.
printName.apply(human, [1]); // Output: "Human Charles1"
// Change this using bind functions
printPersonName(2); // Output: "Person Marian2"
printHumanName(2); // Output: "Person Marian2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment