Skip to main content

Bind Function to Context - Solution & Explanation

MediumPremiumFree on FleetCode3 min read
Practice this problem

Problem Statement

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.boundPolyfill({ "ctx": "My Object" })
boundFunc();

The output should be "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 the built-in Function.bind method.

 

Example 1:

Input: 
fn = function f(multiplier) { 
  return this.x * multiplier; 
}
obj = {"x": 10}
inputs = [5]
Output: 50
Explanation:
const boundFunc = f.bindPolyfill({"x": 10});
boundFunc(5); // 50
A multiplier of 5 is passed as a parameter.
The context is set to {"x": 10}.
Multiplying those two numbers yields 50.

Example 2:

Input: 
fn = function speak() { 
  return "My name is " + this.name; 
}
obj = {"name": "Kathy"}
inputs = []
Output: "My name is Kathy"
Explanation:
const boundFunc = f.bindPolyfill({"name": "Kathy"});
boundFunc(); // "My name is Kathy"

 

Constraints:

  • obj is a non-null object
  • 0 <= inputs.length <= 100

 

Can you solve it without using any built-in methods?

Approach Overview

Problem Overview: You receive a function fn and a context object. The task is to return a new function that always executes fn with this bound to that context, regardless of how the returned function is called.

Approach 1: Wrapper Function Using apply (O(1) time, O(1) space)

Create a new function that wraps the original fn. Inside the wrapper, call fn.apply(context, args) so the this value is explicitly set to the provided context. The wrapper simply forwards all incoming arguments using rest parameters. The key insight is that JavaScript allows overriding the execution context of a function through apply, making it a clean way to emulate Function.prototype.bind. Function creation takes constant time and space since only a closure referencing fn and context is stored.

This approach relies on JavaScript's dynamic function context model and closures. The returned function captures both fn and the context inside its lexical scope. When the wrapper executes, it forwards arguments and forces the correct this binding. Problems like this often appear in discussions around JavaScript fundamentals and closures because they test your understanding of execution context rather than data structures.

Approach 2: Wrapper Function Using call with Spread (O(1) time, O(1) space)

An alternative implementation uses fn.call(context, ...args). Instead of passing arguments as an array, call accepts them individually. The wrapper still captures fn and context in a closure and forwards arguments using the spread operator. The behavior is identical to the apply version, but some developers prefer it because it looks closer to normal function invocation.

Both implementations rely on the same concept: explicitly controlling the this value during invocation. Since no iteration, searching, or additional storage occurs, both runtime and memory usage remain constant. These patterns frequently appear in problems about functions and runtime behavior in JavaScript.

Recommended for interviews: The apply-based wrapper is the most common solution because it cleanly forwards an arbitrary number of arguments without extra handling. Interviewers usually expect you to recognize that apply or call can control execution context. Showing a simple wrapper demonstrates understanding of closures and the this binding model in JavaScript.

Solution

Code

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Wrapper using apply()O(1)O(1)Most common solution when forwarding variable arguments to a bound function
Wrapper using call() with spreadO(1)O(1)Useful when arguments are already expanded or when avoiding array-based invocation
Native bind()O(1)O(1)Production JavaScript when you want built-in binding behavior

Video Solution

Reverse Linked List - Iterative AND Recursive - Leetcode 206 - Python • NeetCode • 539,243 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Bind Function to Context easy or hard?
Bind Function to Context is typically rated Medium because it requires understanding JavaScript execution context rather than implementing a complex algorithm. Developers unfamiliar with this, closures, or apply/call may find it tricky even though the implementation itself is short.
Bind Function to Context Python/Java solution
This problem is designed around JavaScript's this binding behavior, so it does not directly translate to Python or Java. Those languages handle method context differently. In JavaScript or TypeScript, the solution uses closures and apply/call to enforce the desired context.
How to solve Bind Function to Context in O(1)?
Return a new function that internally executes fn.apply(context, args) or fn.call(context, ...args). The returned function captures the context through a closure and forwards all parameters to the original function. Since no loops or extra allocations are involved, both time and space complexity remain O(1).
What is the best approach for Bind Function to Context?
The best approach is creating a wrapper function that calls the original function using fn.apply(context, args). This guarantees the this value is always the provided context. The wrapper captures both the function and the context through a closure, making the implementation simple and efficient with O(1) time and O(1) space.
Is Bind Function to Context asked at Google/Amazon/Meta?
Problems about binding function context appear in JavaScript-focused interviews, especially for frontend roles at companies like Google, Amazon, and Meta. They test understanding of the this keyword, closures, and how function invocation works internally in JavaScript.
What data structure is used in Bind Function to Context?
No traditional data structures such as arrays, stacks, or hash maps are required. The solution relies on JavaScript closures and function invocation utilities like apply or call to control the execution context.
What is the time complexity of Bind Function to Context?
Creating the bound function takes O(1) time because it only returns a wrapper function referencing the original function and context. No iteration or additional data structures are required. Each invocation simply forwards arguments and calls the original function.

Ready to solve this problem?

Practice Bind Function to Context with our built-in code editor and test cases.

Practice on FleetCode