JS Machine Coding Questions — Implementations You Must Know
Custom call & apply
- Trick: Temporarily attach the function as a property of ctx, call it (so this inside becomes ctx), then remove it.
- Using a Symbol avoids overwriting existing properties on ctx.
1Function.prototype.myCall = function (ctx, ...args) {
2 ctx = ctx || globalThis;
3 const sym = Symbol();
4 ctx[sym] = this;
5 const result = ctx[sym](...args);
6 delete ctx[sym];
7 return result;
8};
9
10Function.prototype.myApply = function (ctx, args = []) {
11 return this.myCall(ctx, ...args);
12};