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
INPUTBINDING PROCESSRESULTOriginal Functionfunction(a, b) {return this.n + a + b;Context Object{n: 1}Arguments[2, 3]1Add bindPolyfill toFunction.prototype2Capture original functionand context object3Return new function usingcall() or apply()Bound Functionthis.n = 1 (from context)a = 2, b = 3 (from args)Result: 1 + 2 + 3 = 6ExecutionboundFunc(2, 3)calls original withbound contextKey Insight:JavaScript functions can have their 'this' context dynamically bound using call() or apply() methodsTutorialsPoint - Bind Function to Context | Function.prototype Extension
Asked in
Google 25 Facebook 30 Amazon 20 Microsoft 15
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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