new Operator
JS Functions
Medium
15 min
prototypes
objects
this
functions
Implement myNew(constructor, ...args), which does what new constructor(...args) does for ordinary function constructors, without using the new keyword or Reflect.construct.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ada = myNew(Person, 'Ada');
ada.name; // 'Ada'
ada.greet(); // "Hi, I'm Ada"
ada instanceof Person; // true
function Factory() {
this.ignored = true;
return { custom: true };
}
myNew(Factory); // { custom: true } (an object returned by the constructor wins)
Requirements
- Throw a
TypeErrorifconstructoris not a function. - Create a new object whose prototype is
constructor.prototype. Ifconstructor.prototypeis not an object (someone set it to a primitive ornull), useObject.prototype, as the spec does. - Call
constructorwiththisset to the new object and the given arguments. - If the constructor returns an object or function, return that. Otherwise (no return, or a primitive), return the new object.
- You may use
Object.create(orObject.setPrototypeOf) andapply/call.
Clarification
class constructors can't be called without new, so myNew only needs to support ordinary functions. Explain in your answer why classes are out of reach and what would handle them.
Follow-up
- What is
new.target, and why can'tmyNewset it? - What happens with
newon an arrow function?
Spotted a mistake or a rights concern? Report an issue