Bind Function to Context - Problem
Enhance all JavaScript functions with a custom bindPolyfill method that mimics the behavior of the native Function.prototype.bind() method.
When bindPolyfill is called on a function with an object as an argument, it should return a new function where the this context is permanently bound to the provided object.
Key Requirements:
- Add
bindPolyfillmethod toFunction.prototype - The method accepts a single object parameter
- Return a new function with the bound context
- Cannot use the built-in
Function.prototype.bind()method
Example:
function greet() {
return 'Hello, ' + this.name;
}
const boundGreet = greet.bindPolyfill({name: 'Alice'});
console.log(boundGreet()); // "Hello, Alice" Input & Output
example_1.js โ Basic Binding
$
Input:
function f() { return 'My context is ' + this.ctx; }
const boundFunc = f.bindPolyfill({ "ctx": "My Object" });
boundFunc();
โบ
Output:
"My context is My Object"
๐ก Note:
The function f is bound to an object with ctx property, so when called, this.ctx refers to "My Object"
example_2.js โ Binding with Arguments
$
Input:
function greet(greeting, punctuation) { return greeting + ', ' + this.name + punctuation; }
const boundGreet = greet.bindPolyfill({name: 'Alice'}, 'Hello');
boundGreet('!');
โบ
Output:
"Hello, Alice!"
๐ก Note:
The function is bound with context {name: 'Alice'} and preset argument 'Hello', then called with additional argument '!'
example_3.js โ Multiple Calls
$
Input:
function multiply(factor) { return this.value * factor; }
const obj = {value: 5};
const boundMultiply = multiply.bindPolyfill(obj);
boundMultiply(3);
โบ
Output:
15
๐ก Note:
The bound function maintains the context across multiple calls, always using this.value = 5
Constraints
- The context parameter will always be a non-null object
- Functions may have 0 or more parameters
- The original function should not be modified
- Cannot use Function.prototype.bind()
- Must work with arrow functions and regular functions
Visualization
Tap to expand
Understanding the Visualization
1
Original Function
Function exists without knowing its context (this is undefined)
2
Binding Process
bindPolyfill creates a closure capturing the context object
3
Bound Function
New function always knows its context through the closure
4
Execution
When called, the bound function applies the captured context
Key Takeaway
๐ฏ Key Insight: Closures allow us to permanently associate a context with a function, creating the binding behavior without modifying the original function.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code