xxxxxxxxxx
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Mary",
lastName: "Doe"
}
// This will return "Mary Doe":
person.fullName.apply(person1);
xxxxxxxxxx
let cat = { type: 'Cat', sound: 'Meow' };
let dog = { type: 'Dog', sound: 'Woof' };
const say = function (message) {
console.log(message);
console.log(this.type + ' says ' + this.sound);
};
say.apply(cat, ['What does a cat say?']);
say.apply(dog, ['What does a dog say?']);
Code language: JavaScript (javascript)
xxxxxxxxxx
The apply() method accepts arguments in an array:
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89
The apply() method is similar to the call() method except that it takes the arguments of the functions as an array instead of the individual arguments.
Syntax: functionName.apply(Object to borrow values from, [...argsN])
xxxxxxxxxx
const person = {
firstName: "John",
lastName: "Doe"
}
function greet(greeting, message) {
return `${greeting} ${this.firstName} ${this.lastName}. ${message}`;
}
let result = greet.apply(person, ["Hello", "How are you?"])
console.log(result) // logs "Hello John Doe. How are you?"
// With love @kouqhar
The apply() method allows an object to borrow the method of another object without duplicating the code.
If you use the call() method, you need to pass the arguments of the greet() function separately as follows;let result = greet.call(person, "Hello", "How are you?")
xxxxxxxxxx
const person = {
name: "John Smith",
getNameAndAddress: function(city, country)
{
return this.name+city+country;
}
}
const personWithoutGet = {
name: "Jerry Smithers"}
console.log(person.getNameAndAddress.apply(personWithoutGet, ['Berlin','Germany']));
}
/*you can think of apply() as "stealing someone else's function to use."*/
/* victimBeingStolenFrom.functionName.call(theThief,[any additional parameters as elements in an array]) */
/*notice the second variable personWithoutGet does not have a getName function*/
/*the difference between call and apply is that call accepts additional parameters separately while apply (this A) accepts the parameters as an array*/