Skip to content
Onsite

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:

  1. Create a new object whose prototype is Constructor.prototype (use Object.prototype if Constructor.prototype is not an object).
  2. Call Constructor with this set to that object and args as arguments.
  3. If Constructor returns an object (including an array or function), return that value instead.
  4. 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

Run checks the 3 visible tests, Submit all 9.