We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Call Function with Custom Context

Difficulty: Medium


Problem Description

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).

Key Insights

  • The callPolyfill method allows us to set the this context for a function without using the built-in Function.call method.
  • The additional arguments passed after the object are forwarded to the original function.
  • Proper handling of the context allows for dynamic behavior based on the object passed.

Space and Time Complexity

Time Complexity: O(1) for the context setup, O(n) for invoking the function where n is the number of arguments. Space Complexity: O(1) for the context object, O(n) for the arguments passed.

Solution

To implement callPolyfill, we can create a method on the function prototype. This method will accept an object to set as this context and then collect any additional arguments. We will then use these arguments to invoke the original function, ensuring the correct context is used.


Code Solutions

Function.prototype.callPolyfill = function(obj, ...args) {
    // Capture the function to be called
    const func = this;
    // Return the result of invoking the function with the correct context
    return func.apply(obj, args);
};

// Example usage:
function tax(price, taxRate) {
    return `The cost of the ${this.item} is ${price * taxRate}`;
}

console.log(tax.callPolyfill({item: "burger"}, 10, 1.1)); // "The cost of the burger is 11"
← Back to All Questions