This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
61. create your own `Function.prototype.call`
Here is a possible implementation of myCall
function:
function myCall(func, thisArg, ...args) {
if (typeof func !== 'function') {
throw new TypeError('First argument must be a function');
}
thisArg = thisArg || window; // default to window if not provided
const key = Symbol('temp_key'); // create a unique symbol as the temporary property name
thisArg[key] = func; // attach the function to the thisArg object using the temporary property
const result = thisArg[key](...args); // invoke the function with the given arguments
delete thisArg[key]; // remove the temporary property from the object
return result; // return the result of the function invocation
}
Explanation:
- The
myCall
function takes at least two arguments:func
(the function to be called) andthisArg
(the value ofthis
inside the function). - It also takes zero or more additional arguments (
...args
) that will be passed to the function as its arguments. - If
func
is not a function, it throws aTypeError
. - If
thisArg
is not provided or isnull
/undefined
, it defaults towindow
. - It creates a unique symbol (
key
) as the temporary property name to avoid clash with existing properties. - It attaches the
func
to thethisArg
object using the temporary property. - It invokes the
func
using thethisArg
asthis
and the given arguments (...args
). - It removes the temporary property from the
thisArg
object. - It returns the result of the function invocation.
Example usage:
function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = { name: 'Alice' };
myCall(greet, person, 'Bob');
// Output: "Hello, Bob! My name is Alice."
myCall(greet, null, 'Charlie');
// Output: "Hello, Charlie! My name is undefined." (defaulting to window)