Implement myNew(Ctor, ...args), which does what new Ctor(...args) does for an ordinary constructor function.
- Create a new empty object whose prototype is
Ctor.prototype. IfCtor.prototypeis not an object (for example it was set tonull), useObject.prototypeinstead. - Run
Ctorwith that object asthisand the given arguments. - If
Ctorreturns an object or a function, return that. If it returns a primitive,nullor nothing, return the new object.
Rules:
- Don't use the
newkeyword orReflect.construct. You may useapplyorcall. Ctoris always a plainfunction, never aclass. Classes can't be called withoutnew.- If
Ctoris not a function, throw aTypeError.
Input: function P(n) { this.n = n; }
myNew(P, 3)
Output: { n: 3 }, and Object.getPrototypeOf(result) === P.prototype
Input: function F() { this.a = 1; return { b: 2 }; }
myNew(F)
Output: { b: 2 }a returned object replaces the new one
Input: function G() { this.a = 1; return 5; }
myNew(G)
Output: { a: 1 }a returned primitive is ignored