Call Function with Custom Context - Problem

Enhance all functions to have the callPolyfill method. The method accepts an object obj as its first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on).

For example if you had the function:

function tax(price, taxRate) {
  const totalCost = price * (1 + taxRate);
  console.log(`The cost of ${this.item} is ${totalCost}`);
}

Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined.

However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output.

Please solve this without using the built-in Function.call method.

Input & Output

Example 1 — Tax Calculator with Context
$ Input: function tax(price, taxRate) { return price * (1 + taxRate); }, context = {item: "salad"}, args = [10, 0.1]
Output: 11
💡 Note: The tax function is called with 'this' set to {item: "salad"}, calculating 10 * (1 + 0.1) = 11
Example 2 — Greeting Function
$ Input: function greet(name) { return `Hello ${name}, I am ${this.title}`; }, context = {title: "Dr."}, args = ["Alice"]
Output: "Hello Alice, I am Dr."
💡 Note: The greet function accesses this.title from the provided context object
Example 3 — Multiple Arguments
$ Input: function sum(a, b, c) { return a + b + c + this.offset; }, context = {offset: 100}, args = [1, 2, 3]
Output: 106
💡 Note: Function sums arguments 1+2+3=6, then adds this.offset=100, resulting in 106

Constraints

  • 1 ≤ args.length ≤ 100
  • 0 ≤ JSON.stringify(obj).length ≤ 105
  • Function must work without using built-in call method

Visualization

Tap to expand
Call Function with Custom Context ProblemFunctionfunction tax(price, rate) {return price * (1 + rate)}Context Object{ item: "salad" }this contextArguments[10, 0.1]price, taxRateTemporary Bindingobj[symbol] = functionthis = context objectResult: Function executes with correct 'this' bindingthis.item is accessible as "salad"
Understanding the Visualization
1
Input
Function + Context Object + Arguments
2
Process
Bind function to object as temporary property
3
Output
Function result with correct 'this' context
Key Takeaway
🎯 Key Insight: By temporarily assigning the function as a property on the target object, we leverage JavaScript's method invocation to set the correct 'this' context
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
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