Skip to main content
Back to problems
#2754
Medium JavaScript

Bind function to context

87.2% acceptance
Mar 31, 2026
17
0
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.

Solution

TypeScript
Time O(1)
Space O(1)
LeetCode
solution.ts
type Fn = (...args) => any

interface Function {
  bindPolyfill(obj: Record<any, any>): Fn;
}

Function.prototype.bindPolyfill = function(obj): Fn {
  const fn = this;
  return function(...args) {
    return fn.apply(obj, args);
  };
}