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
- Use a unique
Symbolas a temporary property name so existing properties ofcontextare never overwritten. - Attach the target function (
this) tocontext[symbol], then callcontext[symbol](...args); inside that callthisiscontext. - Delete the temporary property afterwards to restore the object.
- When
contextisnullorundefined, fall back toglobalThis, 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 ofcontext. - Calling
applydirectly: that is the built-in mechanism the exercise wants reimplemented. - Forgetting to delete the temporary property: the passed-in object would be polluted.
- Using
callPolyfillinstead ofthis: the function to invoke is the one the method was called on, namelythis.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.