Skip to main content

custom call method

  • cal method is present on Function prototype ,
  • it accept "this" as first parameter and rest parameter are its argument in comma separated values
function myCall(context, ...args) {
if (typeof this !== "function") {
throw new Error(`not a function`);
}

// Assign the function to the context
context.callingFunction = this;
let res = context.callingFunction(...args);
delete context.callingFunction;
return res;
}

Function.prototype.myCall = myCall;
// Object.prototype.myCall = myCall; // will throw

let a = { a: 1, b: 2 };
let obj = { name: "Shadab" }; // Create an object
function abc(...args) {
console.log(this);
console.log(args);
}
// Attempt to call myCall on the object, which is not a function
try {
abc.myCall(a, 1, 2, 3); // This will give output
// obj.myCall(a, 1, 2, 3); // This will trigger the error
} catch (error) {
console.error("error here", error.message); // Print the error message
}