Skip to main content

function.apply

  • Apply method is present on Function prototype ,
  • It accept "this" (context) as first parameter and rest parameter are its argument in array
function myApply(context, args) {
if (typeof this !== "function") {
throw new Error(`not a function`);
}
context["callingFunction"] = this;
let res = context["callingFunction"](args);
delete context["callingFunction"];
return res;
}

Function.prototype.myApply = myApply;

function abc(args) {
console.log(this.a);
console.log(args);
}

try {
abc.myApply({ a: 1 }, [1, 2, 3, 4]); // This will give output
} catch (error) {
console.error("error here", error.message); // Print the error message
}