Created
November 12, 2022 09:31
-
-
Save Tribhuwan-Joshi/a857cba23f247c4cb8de18978d599711 to your computer and use it in GitHub Desktop.
call vs apply vs bind
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
/* With the call() method, you can write a method that can be used on different objects. */ | |
const person = { | |
fullName: function() { | |
return this.firstName + " " + this.lastName; | |
} | |
} | |
const person1 = { | |
firstName:"John", | |
lastName: "Doe" | |
} | |
const person2 = { | |
firstName:"Mary", | |
lastName: "Doe" | |
} | |
// This will return "John Doe": | |
person.fullName.call(person1); | |
// can pass arguement | |
const person = { | |
fullName: function(city, country) { | |
return this.firstName + " " + this.lastName + "," + city + "," + country; | |
} | |
} | |
const person1 = { | |
firstName:"John", | |
lastName: "Doe" | |
} | |
person.fullName.call(person1, "Oslo", "Norway"); | |
/* With the apply() method, you can write a method that can be used on different objects. */ | |
// same as call() but can pass array as arguments | |
const person = { | |
fullName: function(city, country) { | |
return this.firstName + " " + this.lastName + "," + city + "," + country; | |
} | |
} | |
const person1 = { | |
firstName:"John", | |
lastName: "Doe" | |
} | |
person.fullName.call(person1, "Oslo", "Norway"); | |
// Math.max.apply(null,[1,2,3]) | |
/* With the bind() method, an object can borrow a method from another object. */ | |
// it will return a new function instead of calling it | |
const person = { | |
firstName:"John", | |
lastName: "Doe", | |
display: function () { | |
let x = document.getElementById("demo"); | |
x.innerHTML = this.firstName + " " + this.lastName; | |
} | |
} | |
let display = person.display.bind(person); | |
setTimeout(display, 3000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment