function myFunc(p1, p2, pN)
{
// here "this" will equal myThis
}
let myThis = {};
// call myFunc using myThis as context.
// destructure array to function arguments.
myFunc.apply(myThis, ["param1", "param2", "paramN"]);
The apply() method accepts arguments in an array:
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89
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*/
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Mary",
lastName: "Doe"
}
// This will return "Mary Doe":
person.fullName.apply(person1);
Function.prototype.construct = function(aArgs) {
let oNew = Object.create(this.prototype);
this.apply(oNew, aArgs);
return oNew;
};
Function.prototype.construct = function (aArgs) {
let fNewConstr = new Function("");
fNewConstr.prototype = this.prototype;
let oNew = new fNewConstr();
this.apply(oNew, aArgs);
return oNew;
};