call() and apply()
Call() and apply() functions; It allows sending an object as a parameter to another object and executing the methods of that object.
The difference is that the call() function takes the variables separately.
apply() takes any function arguments as an array.
let person = {
firstName: "Umut",
lastName: "Çakmak",
age: 0,
city: "",
fullName: function () {
return (
this.firstName + " " + this.lastName + " " + this.age + " " + this.city
);
},
personMessage(message) {
return `${message} ${this.firstName}`;
}
};
let people = {
firstName: "Gökhan",
lastName: "Çakmak",
age: 36,
city: "Ankara"
};
let x = person.fullName.call(people);
let y = person.fullName.apply(people);
let z = person.personeMessage.apply(people, ["Hello , My Name is "]);
console.log(x);
console.log(y);
console.log(z);
Output :
//x :Gökhan Çakmak 36 Ankara
//y : Gökhan Çakmak 36 Ankara
//z : Hello , My Name is Gökhan
bind()
var car = {
brand: "Mercedes",
details: function(){
console.log(this.brand);
}
}
//var myCarDetails = car.details;
//myCarDetails();
This won't work because "this" will now be assigned to the global context with no brand attribute.
var car = {
brand: "Mercedes",
details: function(){
console.log(this.brand);
}
}
var myCarDetails = car.details.bind(car);
myCarDetails();
The bind() method creates a new function in "car" in the above case, where "this" refers to the parameter in parentheses. In this way, the bind() method ensures that a function with a specified "this" value is called.
Example ;