⚡Flashcard Drill➔
NeetCode #969LC-2693MediumJavaScript
← Back to All Problems

#969 · #2693 · Call Function with Custom Context(使用自定义上下文调用函数)

📌 Problem Statement & Constraints

Implement Function.prototype.callPolyfill(context, ...args): invoke the function with context bound as this, passing args, and return its result.

💡 Core Algorithmic Approaches

  1. Use a unique Symbol as a temporary property name so existing properties of context are never overwritten.
  2. Attach the target function (this) to context[symbol], then call context[symbol](...args); inside that call this is context.
  3. Delete the temporary property afterwards to restore the object.
  4. When context is null or undefined, fall back to globalThis, matching non-strict behaviour.

💻 Benchmark Python3 Implementation

Function.prototype.callPolyfill = function(context, ...args) {
    const key = Symbol();                     // unique key, avoids clobbering properties
    const ctx = context ?? globalThis;        // null/undefined falls back to the global object
    Object.defineProperty(ctx, key, {
        value: this,
        configurable: true,
        enumerable: false,
    });
    const res = ctx[key](...args);
    delete ctx[key];                          // clean up the temporary property
    return res;
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1): constant time besides the function's own cost.
💾 Space Complexity
O(1): one temporary property.

⚠️ Interview Pitfalls & Follow-ups

  • Using a fixed string property such as fn: it would overwrite a real property of context.
  • Calling apply directly: that is the built-in mechanism the exercise wants reimplemented.
  • Forgetting to delete the temporary property: the passed-in object would be polluted.
  • Using callPolyfill instead of this: the function to invoke is the one the method was called on, namely this.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems