Call Function with Custom Context - Problem
In JavaScript, every function can be called with a specific context (the this value) using methods like call(), apply(), or bind(). Your task is to create a polyfill for the call() method by implementing callPolyfill.
The callPolyfill method should:
- Accept an object
objas the first parameter (this becomes thethiscontext) - Accept any number of additional arguments to pass to the function
- Execute the function with the specified context and arguments
- Important: You cannot use the built-in
Function.callmethod
Example:
function tax(price, taxRate) {
const totalCost = price * (1 + taxRate);
console.log(`The cost of ${this.item} is ${totalCost}`);
}Calling tax(10, 0.1) logs "The cost of undefined is 11" because this.item is undefined.
But tax.callPolyfill({item: "salad"}, 10, 0.1) should log "The cost of salad is 11" with the proper context!
Input & Output
example_1.js โ Basic Function Call
$
Input:
function greet(greeting) {
return `${greeting}, ${this.name}!`;
}
greet.callPolyfill({name: "Alice"}, "Hello")
โบ
Output:
"Hello, Alice!"
๐ก Note:
The function is called with {name: "Alice"} as the context, so this.name becomes "Alice"
example_2.js โ Math Calculation
$
Input:
function tax(price, taxRate) {
return price * (1 + taxRate) + ` for ${this.item}`;
}
tax.callPolyfill({item: "book"}, 20, 0.08)
โบ
Output:
"21.6 for book"
๐ก Note:
The tax calculation uses the provided context to access this.item = "book"
example_3.js โ No Arguments
$
Input:
function getInfo() {
return `${this.name} is ${this.age} years old`;
}
getInfo.callPolyfill({name: "Bob", age: 25})
โบ
Output:
"Bob is 25 years old"
๐ก Note:
Function called with no additional arguments, only context object
Constraints
-
contextcan be any object ornull/undefined - The function can have 0 to 100 parameters
- Function can return any valid JavaScript value
- Cannot use built-in Function.call, Function.apply, or Function.bind
- Must handle edge cases like null context appropriately
Visualization
Tap to expand
Understanding the Visualization
1
Preparation
Create a unique property name and assign function to target object
2
Execution
Call function through object property - 'this' naturally becomes the object
3
Cleanup
Remove temporary property and return the result
Key Takeaway
๐ฏ Key Insight: By temporarily making the function a property of the target object, we leverage JavaScript's natural method invocation behavior where `obj.method()` automatically sets `this` to `obj`.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code