Bind Function to Context Problem
Description
LeetCode Problem 2754.
Enhance all functions to have the bindPolyfill method. When bindPolyfill is called with a passed object obj, that object becomes the this context for the function.
For example, if you had the code:
function f() {
console.log('My context is ' + this.ctx);
}
f();
The output would be "My context is undefined". However, if you bound the function:
function f() {
console.log('My context is ' + this.ctx);
}
const boundFunc = f.boundPolyfill({ "ctx": "My Object" })
boundFunc();
The output should be "My context is My Object".
You may assume that a single non-null object will be passed to the bindPolyfill method.
Please solve it without the built-in Function.bind method.
Example 1:
Input:
fn = function f(multiplier) {
return this.x * multiplier;
}
obj = {"x": 10}
inputs = [5]
Output: 50
Explanation:
const boundFunc = f.bindPolyfill({"x": 10});
boundFunc(5); // 50
A multiplier of 5 is passed as a parameter.
The context is set to {"x": 10}.
Multiplying those two numbers yields 50.
Example 2:
Input:
fn = function speak() {
return "My name is " + this.name;
}
obj = {"name": "Kathy"}
inputs = []
Output: "My name is Kathy"
Explanation:
const boundFunc = f.bindPolyfill({"name": "Kathy"});
boundFunc(); // "My name is Kathy"
Constraints:
objis a non-null object0 <= inputs.length <= 100
Can you solve it without using any built-in methods?
Solution
Approach: Wrap the call with call()
Add bindPolyfill to Function.prototype so every function gets it. Inside it, this is the function being bound. Return a new function that, when called, runs the original with obj as its this and forwards whatever arguments it receives. fn.call(obj, ...args) does exactly that, and we never touch Function.prototype.bind.
Capture the original function in a variable (or use an arrow function) so that it is not confused with the this of the returned function.
Complexity: Time O(1) to bind, plus the cost of the call; space O(1).
/**
* @param {Object} obj
* @return {Function}
*/
Function.prototype.bindPolyfill = function (obj) {
const fn = this;
return function (...args) {
return fn.call(obj, ...args);
};
};