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

Bind Function to Context

Number: 2770

Difficulty: Medium

Paid? Yes

Companies: N/A


Problem Description

Enhance all functions with a bindPolyfill method. When bindPolyfill is called with a specific non-null object, that object becomes the this context for the function. The returned function should forward any arguments to the original function, and when executed, it should invoke the original function with the provided context.


Key Insights

  • Extend Function.prototype to add the bindPolyfill method.
  • Capture the original function, and return a new function that uses the passed context as its this.
  • To emulate binding without using .bind, temporarily assign the function to the passed object and invoke it.
  • Ensure all arguments passed to the new function are properly forwarded to the original function.

Space and Time Complexity

Time Complexity: O(n) per call, where n is the number of arguments forwarded. Space Complexity: O(1), aside from the space used for the passed arguments.


Solution

The solution extends the Function prototype by adding a bindPolyfill method which captures the original function. When bindPolyfill is called with a context object, it returns a new function. This new function creates a temporary unique property on the context object to store the original function, and then calls that function using that context with the provided arguments. After the call, it deletes the temporary property. This technique mimics binding by ensuring the this inside the original function refers to the given object.


Code Solutions

// Extend the Function prototype with a custom bindPolyfill method
Function.prototype.bindPolyfill = function(context) {
    // Save a reference to the original function
    var originalFunction = this;
    // Return a new function that applies the originalFunction with the provided context
    return function() {
        // Generate a unique key to avoid collision with existing properties on context
        var uniqueKey = '__tempFunc__';
        while (context.hasOwnProperty(uniqueKey)) {
            uniqueKey += '_';
        }
        // Temporarily assign the original function to the context using the unique key
        context[uniqueKey] = originalFunction;
        // Convert arguments to an array
        var args = [];
        for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        // Call the function with the provided context and arguments
        var result = context[uniqueKey](...args);
        // Remove the temporary function property from the context
        delete context[uniqueKey];
        // Return the result of the function call
        return result;
    }
};

// Example usage:
function f(multiplier) {
    return this.x * multiplier;
}
var obj = { x: 10 };
var boundFunc = f.bindPolyfill(obj);
console.log(boundFunc(5)); // 50

function speak() {
  return "My name is " + this.name;
}
var person = { name: "Kathy" };
var boundSpeak = speak.bindPolyfill(person);
console.log(boundSpeak()); // "My name is Kathy"
← Back to All Questions