Bind Function to Context - Problem

Enhance all functions to have a 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(); // Output: "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(); // Output: "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 using the built-in Function.bind method.

Input & Output

Example 1 — Basic Binding
$ Input: function f() { console.log('My context is ' + this.ctx); } f.bindPolyfill({ "ctx": "My Object" })()
Output: My context is My Object
💡 Note: The function f is bound to the object {ctx: 'My Object'}, so when called, this.ctx refers to 'My Object'
Example 2 — Multiple Properties
$ Input: function greet() { return this.name + ' says ' + this.message; } greet.bindPolyfill({ name: 'Alice', message: 'Hello' })()
Output: Alice says Hello
💡 Note: Function accesses multiple properties from the bound context object
Example 3 — With Arguments
$ Input: function add(a, b) { return this.base + a + b; } add.bindPolyfill({ base: 10 })(3, 5)
Output: 18
💡 Note: Bound function can still accept arguments: 10 + 3 + 5 = 18

Constraints

  • The bindPolyfill method should be added to Function.prototype
  • The method should accept a single object parameter
  • The returned function should maintain the original function's behavior
  • Arguments should be properly forwarded to the original function

Visualization

Tap to expand
Bind Function to Context - Problem OverviewOriginal Functionfunction f() { console.log(this.ctx);}bindPolyfill Processf.bindPolyfill({ ctx: "My Object"})Bound FunctionboundFunc()→ "My context isMy Object"ImplementationFunction.prototype.bindPolyfill = function(obj) { return (...args) => this.call(obj, ...args);};
Understanding the Visualization
1
Input
Original function with no context
2
Process
bindPolyfill method creates wrapper with fixed context
3
Output
Bound function that always uses specified context
Key Takeaway
🎯 Key Insight: Function binding is creating a wrapper that preserves context using call or apply
Asked in
Google 25 Meta 30 Amazon 20 Netflix 15
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen