The task is to implement function.prototype.call().
The boilerplate code
Function.prototype.mycall = function(thisArg, ...args) {
// your code here
}
function.prototype.call is useful when the this of a function is to be altered. First, ensure that this is callable
if(typeof this !== "function") {
throw new TypeError("mycall must be a function");
}
Handle null/undefined by converting them to the global object.
if (thisArg === null || thisArg === undefined) {
thisArg = globalThis;
}
If the arguments are primitive, transform them to objects
else {
thisArg = Object(thisArg);
}
Create a unique property to avoid collisions
const fnKey = Symbol("fn");
Temporarily attach function to thisArg
thisArg[fnKey] = this
Invoke function with the provided arguments
const result = thisArg[fnKey](...args);
Clean up after execution
delete thisArg[fnKey];
Return the result
return result;
The final code
Function.prototype.mycall = function(thisArg, ...args) {
// your code here
if(typeof this !== "function") {
throw new TypeError("mycall must be a function");
}
if(thisArg === null || thisArg === undefined) {
thisArg = globalThis;
} else {
thisArg = Object(thisArg);
}
const fnKey = Symbol("fn");
thisArg[fnKey] = this;
const result = thisArg[fnKey](...args);
delete thisArg[fnKey];
return result;
}
That's all folks!
Top comments (0)