Talentd
FleetCode
Make and follow sheets.Sign in

Call Function with Custom Context solution and explanation

Medium5 min read79.0% acceptanceUpdated 9 Apr 2026
Call Function with Custom Context - Leetcode 2693 - JavaScript 30-Day ChallengeNeetCodeIO · 8:16 · 2K viewsWatch on YouTube
5 more videos on this problem
  1. Call Function with Custom Context - Leetcode 2693 - JavaScript 30-Day ChallengeNeetCodeIO · 8:16 · 2K views
  2. Day 26. LeetCode 2693. Call Function with Custom Context. Daily JS challengeКанал про вирішення ЛітКод Українською · 7:04 · 163 views
  3. Leetcode Grind - День 75. Call Function with Custom ContextMark Brut [IT] · 30:33 · 137 views
  4. 2693. Call Function with Custom Context - Day 26/30 Leetcode Javascript ChallengeProgramming Live with Larry · 20:27 · 113 views
  5. Call Function with Custom Context - LeetCode 2693 - JavaScript - JS 30 Day Challenge Day 26Alpha-Code · 8:36 · 59 views
  6. JavaScript Solving LeetCode Challenge 26 with 'apply' - Call Function with Custom Context - 2693vanAmsen · 3:18 · 42 views

The 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.

Example 1:

Input:
fn = function add(b) {
  return this.a + b;
}
args = [{"a": 5}, 7]
Output: 12
Explanation:
fn.callPolyfill({"a": 5}, 7); // 12
callPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument.

Example 2:

Input: 
fn = function tax(price, taxRate) { 
 return `The cost of the ${this.item} is ${price * taxRate}`; 
}
args = [{"item": "burger"}, 10, 1.1]
Output: "The cost of the burger is 11"
Explanation: callPolyfill sets the "this" context to {"item": "burger"}. 10 and 1.1 are passed as additional arguments.

Constraints:

  • typeof args[0] == 'object' and args[0] != null
  • 1 <= args.length <= 100
  • 2 <= JSON.stringify(args[0]).length <= 105

Approach overview

Problem Overview: You need to execute a function using a custom this context, similar to how Function.prototype.call works in JavaScript. The task is to attach the function to a provided object and invoke it so that the object becomes the execution context.

Approach 1: Modify Function Constructor (O(k) time, O(1) space)

This approach mimics how call works internally. Temporarily attach the function to the provided context object, invoke it, then remove it. Because property names may collide with existing keys, a Symbol can be used as a temporary property to guarantee uniqueness. The function is executed using context[tempKey](...args), which forces this to reference the context object. The time complexity is O(k), where k is the number of arguments passed to the function, and the space overhead stays O(1) since only a single temporary property is created.

This method directly demonstrates how dynamic method binding works in JavaScript. Interviewers often prefer this approach because it shows understanding of how functions interact with object contexts and prototype methods.

Approach 2: Using Closures (O(k) time, O(1) space)

A closure-based implementation captures the function and context inside a wrapper function. Instead of modifying the context object, you create a new function that internally invokes the original function while explicitly controlling the execution context. This can be done with apply, bind, or equivalent constructs depending on the language. The closure retains references to the function and context, ensuring that whenever the wrapper runs, the correct this value is used.

The key idea is lexical capture. The wrapper function stores both the target function and the object that should act as its context. When executed, the wrapper forwards the argument list and ensures the correct binding. The runtime cost is still O(k) because the argument list must be forwarded during invocation, while memory usage remains O(1). This pattern appears frequently when working with closures or higher‑order functions.

Closure-based solutions are often easier to reason about in languages that support functional constructs, but they do not demonstrate the internal mechanism of context binding as clearly as the property-attachment technique.

Recommended for interviews: The temporary property approach is typically expected. It shows you understand how this binding works under the hood and how functions behave when attached to objects. Mentioning the closure-based alternative demonstrates deeper knowledge of functional patterns and language design.

Approach 1: Approach 1: Modify Function Constructor

The first approach involves augmenting the Function prototype to add our custom callPolyfill method. This method should simulate the behavior of the native Function.prototype.call method. We'll save the original context of this, invoke our function with the given context, and apply the additional arguments.

def callPolyfill(fn, obj, *args):
    bound_method = fn.__get__(obj, type(obj))
    return bound_method(*args)
Function.prototype.callPolyfill = function(obj, ...args) {
  const uniqueID = Symbol('context');
  obj[uniqueID] = this;
  const result = obj[uniqueID](...args);
  delete obj[uniqueID];
  return result;
};

This solution utilizes Python's method binding. The __get__ descriptor method is used to bind our function to the given object, thereby setting the self context. We then call this bound method with the given arguments.

Complexity

Time Complexity: O(1) — The time to bind a method and invoke it is constant.
Space Complexity: O(1) — We are not storing additional data structures.

Try this approach in the editor

Approach 2: Approach 2: Using Closures

This approach leverages closures to encapsulate the function call logic. By using an immediately invoked function expression (IIFE), we can create a local scope that captures the context and arguments for the function call.

import java.lang.reflect.Method;

public class FunctionPolyfill {
  public static Object callPolyfill(Object obj, Method method, Object... args) throws Exception {
      return method.invoke(obj, args);
  }
}
Function.prototype.callPolyfill = function(obj, ...args) {
  return (() => this.apply(obj, args))();
};

This Java solution makes use of reflection to invoke a method with the specified context. While Java doesn't directly support JavaScript-like binding, using Method.invoke on a specific instance achieves a similar effect.

Complexity

Time Complexity: O(1) — Invocation is based on reflection, which operates in constant time.
Space Complexity: O(1) — Reflection does not impose additional space requirements beyond basic invocation.

Try this approach in the editor

Approach 3: Default Approach

declare global {
    interface Function {
        callPolyfill(context: Record<any, any>, ...args: any[]): any;
    }
}

Function.prototype.callPolyfill = function (context, ...args): any {
    const fn = this.bind(context);
    return fn(...args);
};

/**
 * function increment() { this.count++; return this.count; }
 * increment.callPolyfill({count: 1}); // 2
 */
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Modify Function Constructor

Time Complexity: O(1) — The time to bind a method and invoke it is constant.
Space Complexity: O(1) — We are not storing additional data structures.

Approach 2: Using Closures

Time Complexity: O(1) — Invocation is based on reflection, which operates in constant time.
Space Complexity: O(1) — Reflection does not impose additional space requirements beyond basic invocation.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Modify Function ConstructorO(k)O(1)Best when demonstrating how this binding works internally in JavaScript
Using ClosuresO(k)O(1)When using functional patterns or avoiding mutation of the context object

Frequently asked questions

Is Call Function with Custom Context easy or hard?

The problem is rated Medium because it requires understanding how function context works internally. Developers familiar with JavaScript's call, apply, and bind methods usually solve it quickly, but it can be tricky for those unfamiliar with how this binding is implemented.

Call Function with Custom Context Python/Java solution

In Python, a similar effect can be achieved by explicitly passing the object as the first parameter to the function. In Java or other languages with closures, a wrapper function or lambda can capture the target object and call the method with the correct context. The core idea remains controlling which object acts as the function's execution context.

How to solve Call Function with Custom Context in O(n)?

The problem can be solved in O(k) time by temporarily attaching the function to the provided context object and invoking it with the supplied arguments. Using a unique key such as a Symbol avoids property collisions. After execution, the temporary property is deleted to restore the original object structure.

What is the best approach for Call Function with Custom Context?

The temporary property technique that attaches the function to the context object is the most common solution. It closely mirrors how JavaScript's Function.prototype.call works internally. The function is assigned to the object, invoked with arguments, and then removed. This runs in O(k) time where k is the number of arguments and uses O(1) extra space.

Is Call Function with Custom Context asked at Google/Amazon/Meta?

Problems involving function binding, closures, and JavaScript internals appear in frontend and full‑stack interviews at companies like Google, Amazon, and Meta. While the exact problem may vary, understanding how call, apply, and bind work is commonly tested in JavaScript-focused interviews.

What data structure is used in Call Function with Custom Context?

No complex data structures are required. The solution primarily relies on JavaScript objects to temporarily store the function reference and execute it with the correct this context. In some implementations a Symbol is used to safely create a unique temporary property.

What is the time complexity of Call Function with Custom Context?

The time complexity is O(k), where k represents the number of arguments passed to the function. The implementation mainly forwards arguments during invocation. No loops over large data structures are required, so the complexity scales only with the argument list size.

Comments

Now write it yourselfClose this page and solve Call Function with Custom Context in the editor, without looking.
Practise Call Function with Custom Context