FrontendInterviews.dev

Loading problem…

40. Function.prototype.apply

Easy•

The Function.prototype.apply() method invokes a function immediately with a specified this value and arguments provided as an array.

Implement your own Function.prototype.apply without using the native call, apply, or bind methods. To avoid overriding the built-in method, implement it as Function.prototype.myApply.

Example

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const user = { name: "Alice" };

greet.myApply(user, ["Hi", "!"]); // "Hi, Alice!"

Constraints

  • Native prohibition: Do not use `Function.prototype.call`, `apply`, or `bind`.
  • Property safety: Use a `Symbol()` as the temporary property key to avoid name collisions or overwriting existing properties.
  • Cleanup integrity: Use a `try...finally` block to ensure the temporary property is deleted from the context even if the function throws an error.
  • Context precision: Fall back to `globalThis` for all nullish context inputs.
Accepted23/46|Acceptance Rate50.0%