Implement two standalone functions that run fn with a chosen this:
myCall(fn, thisArg, ...args)passes the arguments one by one.myApply(fn, thisArg, args)takes the arguments as one array or array-like (an object withlengthand numbered keys). A missing ornullargsmeans no arguments.
Both return whatever fn returns. Rules:
- Don't use
Function.prototype.call,applyorbind, and don't useReflect.apply. Don't modifyFunction.prototype. - If
thisArgisnullorundefined, runfnwithglobalThisasthis. A primitivethisArgsuch as2.25is wrapped in its object form, so number methods still work on it. thisArgmust look exactly the same afterwards: no leftover properties, even iffnthrows. It may already have a property with any name, such asfn.- If
fnis not a function, throw aTypeError.
Input: myCall(function (g) { return g + ' ' + this.name; }, { name: 'Ada' }, 'Hi')
Output: 'Hi Ada'
Input: myApply(Math.max, null, [3, 9, 4])
Output: 9