Implement myNew(Constructor, ...args) so it does what the new operator does.
myNew(Constructor, ...args) creates an object whose prototype is Constructor.prototype, then runs Constructor with this set to that object and with args as its arguments. If Constructor.prototype isn't an object, the new object's prototype is Object.prototype, as with new.
It returns the new object, unless the constructor returns an object or a function: then that value is returned instead. Any other return value, such as a number or null, is ignored.
Throw a TypeError if Constructor isn't a function.
Ordinary constructor functions are enough; you don't need to support classes.
function myNew(Constructor, ...args) {
// your code
}
// function Person(name) { this.name = name; }
// Person.prototype.hi = function () { return "Hi, " + this.name; };
// const ada = myNew(Person, "Ada");
// ada.hi(); // "Hi, Ada"
// ada instanceof Person; // true
//
// function Car() { this.make = "Ford"; return { make: "Tesla" }; }
// myNew(Car).make; // "Tesla": the returned object wins
// function Bike() { this.make = "BMX"; return "ignored"; }
// myNew(Bike).make; // "BMX": a returned string is ignored
// myNew(42); // throws a TypeError
Solve it in the editor, with tests
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…