new Operator Implementation
MediumP3Coding
Implement myNew(Constructor, ...args), which does what new Constructor(...args) does, without using the new operator.
Constructor is an ordinary constructor function (not a class or an arrow function). Follow the rules of new:
- Create a new object whose prototype is
Constructor.prototype(useObject.prototypeifConstructor.prototypeis not an object). - Call
Constructorwiththisset to that object andargsas arguments. - If
Constructorreturns an object (including an array or function), return that value instead. - Otherwise return the new object, ignoring any primitive return value.
Example 1
- Input
- function P(name) { this.name = name; } P.prototype.hi = function () { return 'hi ' + this.name; }; myNew(P, 'Ada').hi()
- Output
- 'hi Ada'
Constraints
- Constructor is a plain function.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.