Problem
Enhance all functions to have the callPolyfill
method. The method accepts an object obj
as its first parameter and any number of additional arguments.
The obj
becomes the this
context for the function. The additional arguments are passed to the function (that the callPolyfill
method belongs on).
For example if you had the function:
|
|
Calling this function like tax(10, 0.1)
will log "The cost of undefined is 11"
. This is because the this
context was not defined.
However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1)
will log "The cost of salad is 11"
. The this
context was appropriately set, and the function logged an appropriate output.
Please solve this without using the built-in Function.call
method.
Examples
Example 1
|
|
Example 2
|
|
Constraints
typeof args[0] == 'object' and args[0] != null
1 <= args.length <= 100
2 <= JSON.stringify(args[0]).length <= 10^5
Solution
Method 1 – Attach to Function Prototype and Use Temporary Property
Intuition
To simulate the call
method without using Function.call
, we can temporarily assign the function as a property of the context object, call it, and then remove the property. This ensures the function executes with the correct this
value.
Approach
- Add a method
callPolyfill
toFunction.prototype
. - In
callPolyfill
, assign the function (this
) as a temporary property on the context object. - Call the function with the provided arguments, using the context as
this
. - Delete the temporary property after calling.
- Return the result.
Code
|
|
|
|
Complexity
- ⏰ Time complexity: O(1)
- 🧺 Space complexity: O(1)