Sub topic 10
What new Actually Does
This chapter assumes you know how to write a constructor function and attach methods to its prototype property, which the previous chapter covered. You should also know what Object.create and Object.getPrototypeOf do, and how this is bound when a function is called as a method. Here we open up the new operator: the exact steps it performs, how to rebuild it by hand, and the edge cases that surprise people.
The four steps of new
When you write new Person('Ada'), the engine does roughly this:
- It creates a fresh, empty object.
- It sets that object's
[[Prototype]]link toPerson.prototype. IfPerson.prototypeis not an object, it usesObject.prototypeinstead. - It calls
Personwiththisbound to the new object and passes along the arguments. - If
Personreturns an object, that object is the result of thenewexpression. Otherwise the result is the object from step 1.
Step 2 is what connects instances to shared methods. Step 4 is the one people forget.
Rebuilding new by hand
Writing your own version is the best way to check that you understand the steps. The function below works for ordinary constructor functions:
function isObject(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function');
}
function myNew(Constructor, ...args) {
if (typeof Constructor !== 'function') {
throw new TypeError('Constructor must be a function');
}
// Steps 1 and 2: create the object and link its prototype
const proto = isObject(Constructor.prototype) ? Constructor.prototype : Object.prototype;
const obj = Object.create(proto);
// Step 3: run the constructor with this = obj
const result = Constructor.apply(obj, args);
// Step 4: an explicitly returned object wins
return isObject(result) ? result : obj;
}
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ada = myNew(Person, 'Ada');
console.log(ada.greet()); // "Hi, I'm Ada"
console.log(Object.getPrototypeOf(ada) === Person.prototype); // true
console.log(ada instanceof Person); // trueEdge case: what the constructor returns
Return values from a constructor are usually ignored, but only primitive ones. Any returned object, including arrays and functions, replaces the newly created instance.
function ReturnsPrimitive() {
this.a = 1;
return 42; // ignored
}
function ReturnsObject() {
this.a = 1;
return { b: 2 }; // replaces the new instance
}
const p = new ReturnsPrimitive();
const o = new ReturnsObject();
console.log(p); // ReturnsPrimitive { a: 1 }
console.log(o); // { b: 2 }
console.log(o instanceof ReturnsObject); // falseThe object that this pointed to inside ReturnsObject is thrown away. Because the returned object was built from a literal, it links to Object.prototype, so instanceof fails. Sometimes this behavior is used on purpose, for example to return a cached instance. Most of the time it is a bug.
Edge case: a non-object prototype
If someone sets F.prototype to a primitive, new falls back to Object.prototype and does not throw:
function F() {}
F.prototype = 5;
const f = new F();
console.log(Object.getPrototypeOf(f) === Object.prototype); // trueForgetting new
A constructor function is still a plain function, so nothing prevents someone from calling it without new. What happens next depends on strict mode:
| Call | Sloppy mode | Strict mode |
|---|---|---|
| `new Person('Ada')` | New instance | New instance |
| `Person('Ada')` | `this` is the global object, so a global `name` is created and the call returns `undefined` | `this` is `undefined`, so `this.name = ...` throws a TypeError |
Code in ES modules and inside class bodies always runs in strict mode, which turns this silent bug into a loud one. In older code you can guard against the mistake with new.target. It holds the constructor when the function is called with new and is undefined otherwise:
'use strict';
function Point(x, y) {
if (!new.target) {
return new Point(x, y); // repair the call instead of failing
}
this.x = x;
this.y = y;
}
const a = new Point(1, 2);
const b = Point(3, 4); // works thanks to the guard
console.log(a instanceof Point, b instanceof Point); // true trueWhat cannot be called with new
Only functions that have an internal [[Construct]] behavior work with new. Regular function declarations and expressions have it, and so do classes. Several other kinds of function do not:
const arrow = () => {};
const obj = { method() {} };
async function load() {}
for (const fn of [arrow, obj.method, load]) {
try {
new fn();
} catch (err) {
console.log(err instanceof TypeError, err.message);
}
}
// true "arrow is not a constructor"
// true "obj.method is not a constructor"
// true "load is not a constructor"Arrow functions, method shorthand, async functions, and generators have no prototype property meant for instances and no [[Construct]], so new rejects them right away. Classes work the other way round: they can only be called with new, and calling Person() on a class throws even in sloppy mode.
Common errors
- Returning
thisexplicitly is harmless but unnecessary, becausenewalready returns the instance. - Returning an object "just to add fields" throws away the prototype link, and instances lose their methods.
- Using an arrow function as a constructor fails at the
newcall, not where the function is defined. - Calling a constructor without
newin sloppy mode leaks properties onto the global object without any error.
Exercise
Given function Box(v) { this.v = v; return [v]; }, what does new Box(3) evaluate to, and is it instanceof Box?
Show answer
It evaluates to the array [3]. Arrays are objects, so step 4 replaces the new instance with the array. The array's prototype is Array.prototype, not Box.prototype, so new Box(3) instanceof Box is false.
Exercise
Why does myNew in this chapter fail with class Cat {}, and what built-in should you use instead?
Show answer
myNew calls Constructor.apply(obj, args), and class constructors throw a TypeError when called without new. Use Reflect.construct(Cat, args), which runs the real construct behavior and sets new.target.
Exercise
In strict mode, what happens when you call function User(n) { this.n = n; } as User('x') without new? How would you make the call work anyway?
Show answer
this is undefined, so assigning this.n throws a TypeError. Add a guard at the top: if (!new.target) return new User(n);.