What does the new keyword actually do?
The equivalent function is short, and writing it out by hand is the fastest way to be certain that you understand what the keyword really does.
function myNew(Constructor) {
const args = Array.prototype.slice.call(arguments, 1);
// 1. Create a fresh object whose prototype is Constructor.prototype.
const instance = Object.create(Constructor.prototype);
// 2. Run the constructor with this bound to the new object.
const result = Constructor.apply(instance, args);
// 3. Return the result if it is an object, otherwise the new object.
if (result !== null && typeof result === 'object') {
return result;
}
return instance;
}
function Point(x, y) {
this.x = x;
this.y = y;
}
const p = myNew(Point, 3, 4);
console.log(p.x, p.y); // 3 4
console.log(p instanceof Point); // trueEvery part of that function maps directly onto one step of the real thing. The Object.create call sets the prototype, which is the reason the instanceof check at the end works. The apply call runs the constructor with the right receiver and forwards the arguments, which is the reason the constructor body sees this as the new object. The last few lines take care of the rule about the return value.
The one simplification here is that a real implementation also checks whether the thing you passed is a function at all, and it throws a TypeError when it is not. A real implementation also does the prototype linking in a way that you cannot observe from the outside. For understanding the meaning of the keyword, this shorter version is complete enough.
This pattern is worth being able to write because it explains two other things. It explains why arrow functions cannot be used as constructors, because they have no prototype property for the first step to link to. It also explains why a constructor that returns an object can bypass the normal rules completely, because the third step lets it substitute a different result.