Skip to content

Instantly share code, notes, and snippets.

@Tribhuwan-Joshi
Created November 12, 2022 09:31
Show Gist options
  • Save Tribhuwan-Joshi/a857cba23f247c4cb8de18978d599711 to your computer and use it in GitHub Desktop.
Save Tribhuwan-Joshi/a857cba23f247c4cb8de18978d599711 to your computer and use it in GitHub Desktop.
call vs apply vs bind
/* 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