|
| 1 | +```js |
| 2 | +/** |
| 3 | + * Implements a custom version of Function.prototype.call |
| 4 | + * |
| 5 | + * @param {Object} thisArg - The value to use as `this` inside the function. |
| 6 | + * @param {...any} argArray - Arguments to pass to the function. |
| 7 | + */ |
| 8 | +Function.prototype.myCall = function (thisArg, ...argArray) { |
| 9 | + if (typeof this !== 'function') { |
| 10 | + throw new TypeError('myCall must be called on a function'); |
| 11 | + } |
| 12 | + |
| 13 | + // Ensuring `thisArg` is an object (or `null`/`undefined`) |
| 14 | + thisArg = thisArg !== undefined && thisArg !== null ? Object(thisArg) : globalThis; |
| 15 | + |
| 16 | + // Assign the function to a temporary property on `thisArg` |
| 17 | + const uniqueSymbol = Symbol('tempFunction'); // Ensures no collisions with existing properties |
| 18 | + thisArg[uniqueSymbol] = this; |
| 19 | + |
| 20 | + // Invoke the function using the provided arguments |
| 21 | + const result = thisArg[uniqueSymbol](...argArray); |
| 22 | + |
| 23 | + // Clean up: Remove the temporary property from `thisArg` |
| 24 | + delete thisArg[uniqueSymbol]; |
| 25 | + |
| 26 | + return result; // Return the result of the function call |
| 27 | +}; |
| 28 | +``` |
| 29 | + |
| 30 | +### Explanation |
| 31 | +#### Ensure Valid Input: |
| 32 | + |
| 33 | +* If this (the function being called) is not a function, throw a TypeError. |
| 34 | +* This ensures that myCall is only called on valid function objects. |
| 35 | +#### Handle thisArg: |
| 36 | + |
| 37 | +Convert thisArg into an object, unless it’s null or undefined. If thisArg is null or undefined, default to the global object (globalThis in modern JavaScript environments). |
| 38 | +#### Assign Function to Temporary Property: |
| 39 | + |
| 40 | +* Create a unique property with a Symbol (to avoid property name collisions). |
| 41 | +* Temporarily assign the function being invoked (this) to this property on thisArg. |
| 42 | +#### Invoke the Function: |
| 43 | + |
| 44 | +Use the temporary property to call the function with the correct this context and pass in the arguments (...argArray). |
| 45 | +#### Clean Up: |
| 46 | + |
| 47 | +Delete the temporary property after invoking the function to avoid modifying the original object permanently. |
| 48 | +#### Return the Result: |
| 49 | + |
| 50 | +Return the value produced by the invocation of the function. |
| 51 | + |
| 52 | +### Edge Cases |
| 53 | +* `Null` or `Undefined` thisArg: If thisArg is null or undefined, the global object (globalThis) is used as the context. |
| 54 | + |
| 55 | +* Primitive Values for `thisArg`: Primitive values (e.g., 42, "hello", true) are automatically boxed into their respective object wrappers (Number, String, Boolean). |
0 commit comments