Skip to content

2693. Call Function with Custom Context 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };

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

Function.prototype.callPolyfill = function (context, ...args): JSONValue {
  const fn = this;
  Object.defineProperty(context, '__fn__', {
    value: fn,
    enumerable: false,
  });
  const ans = (context.__fn__ as any)(...args);
  delete context.__fn__;
  return typeof ans !== 'undefined' ? ans : undefined;
};