Bind Function to Context - Problem
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.bindPolyfill({ "ctx": "My Object" })
boundFunc();The output should be "My context is My Object".
Note: 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.
Input & Output
Example 1 — Basic Addition
$
Input:
fn = function(a, b) { return this.n + a + b; }, obj = {"n": 1}, inputs = [2, 3]
›
Output:
6
💡 Note:
The bound function has this.n = 1, then adds arguments 2 + 3, total: 1 + 2 + 3 = 6
Example 2 — String Context
$
Input:
fn = function() { return 'My context is ' + this.ctx; }, obj = {"ctx": "My Object"}, inputs = []
›
Output:
"My context is My Object"
💡 Note:
Function accesses this.ctx from bound context object, returning the concatenated string
Example 3 — Multiple Properties
$
Input:
fn = function(x) { return this.a * this.b + x; }, obj = {"a": 2, "b": 3}, inputs = [5]
›
Output:
11
💡 Note:
Context has a=2, b=3. Function computes: 2 * 3 + 5 = 6 + 5 = 11
Constraints
- The function will be called with a single non-null object
- The object may contain any valid JSON properties
- Arguments array can be empty or contain multiple values
- Function may access any properties from the bound context
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code