Sub topic 2
Constructors and Creating Instances with new
This chapter assumes you can write functions with default parameters and destructuring, know how plain objects and property access work, and have a rough idea of what this means. You should also have read the previous chapter on declaring a class. Here we look at the constructor method and at what the new operator does when it creates an instance.
What the constructor is for
A constructor is a special method named constructor that runs once for every new instance. Its job is to put the new object into a valid starting state. Usually that means copying arguments onto this, the object being built.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const a = new Point(0, 0);
const b = new Point(3, 4);
console.log(a.x, a.y); // 0 0
console.log(b.x, b.y); // 3 4
console.log(a === b); // falseEach call to new Point(...) produces a separate object with its own x and y. Changing b.x has no effect on a.
What new does, step by step
When you write new Point(3, 4), the engine performs these steps:
- It creates a fresh, empty object.
- It links that object to
Point.prototype, so the object can use the methods defined in the class body. - It runs the constructor with
thisset to the new object and passes3and4as arguments. - If the constructor returns an object,
newproduces that object. Otherwisenewproduces the object from step 1.
A later chapter covers the prototype link in step 2. For now, the key fact is that this inside the constructor is the object new is about to give back.
The default constructor
The constructor is optional. If you leave it out, JavaScript supplies an empty one. For a base class it behaves like constructor() {}.
class Empty {}
const e = new Empty();
console.log(typeof e); // "object"A class body can contain at most one method named constructor. A second one is a SyntaxError, and the script won't even start. JavaScript has no constructor overloading. If you want several ways to construct an instance, handle the variations inside the single constructor, or write separate factory functions.
Parameters: defaults, options objects, and validation
A constructor's parameters work like the parameters of any other function, so default values and destructuring both work.
class Connection {
constructor(host, { port = 443, secure = true, timeoutMs = 5000 } = {}) {
if (typeof host !== 'string' || host.length === 0) {
throw new TypeError('host must be a non-empty string');
}
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new RangeError(`invalid port: ${port}`);
}
this.host = host;
this.port = port;
this.secure = secure;
this.timeoutMs = timeoutMs;
}
}
const c1 = new Connection('example.com');
const c2 = new Connection('localhost', { port: 8080, secure: false });
console.log(c1.port, c1.secure); // 443 true
console.log(c2.port, c2.secure); // 8080 false
try {
new Connection('db', { port: 70000 });
} catch (err) {
console.log(err.name, err.message); // RangeError invalid port: 70000
}There are three things to notice in this example:
- The
= {}after the destructuring pattern lets callers leave out the options object entirely. Without it,new Connection('example.com')would throw, because you can't destructureundefined. - When a constructor throws,
newnever produces an object. The caller gets the exception and no half-built instance exists. - Validating in the constructor means every instance that exists is valid. The rest of the class doesn't need to check again.
Edge case: shared mutable arguments
A default value is evaluated again on every call, so items = [] gives each instance its own array. An argument the caller passes in is a different matter. That array is shared by reference.
class Cart {
constructor(items = []) {
this.items = items;
}
}
const seed = ['apple'];
const cartA = new Cart(seed);
const cartB = new Cart(seed);
cartA.items.push('pear');
console.log(cartB.items); // ['apple', 'pear'] (shared!)
class SafeCart {
constructor(items = []) {
this.items = [...items];
}
}
const safeA = new SafeCart(seed);
const safeB = new SafeCart(seed);
safeA.items.push('plum');
console.log(safeB.items.includes('plum')); // falseIf an instance should own its state, copy mutable arguments in the constructor.
Return values from a constructor
Most constructors return nothing, and new hands back this. If you do return something, it matters what type it is:
| Constructor returns | Result of `new` |
|---|---|
| Nothing, or `undefined` | The newly created `this` |
| A primitive (number, string, `null`, ...) | The newly created `this`; the return value is ignored |
| An object (including arrays and functions) | That returned object; `this` is discarded |
class Primitive {
constructor() {
this.kind = 'instance';
return 42;
}
}
console.log(new Primitive().kind); // 'instance'
const cache = new Map();
class Color {
constructor(name) {
if (cache.has(name)) {
return cache.get(name);
}
this.name = name;
cache.set(name, this);
}
}
const red1 = new Color('red');
const red2 = new Color('red');
console.log(red1 === red2); // trueThe Color class uses the object-return rule to reuse instances. The trick works, but it surprises readers, because new normally promises a fresh object. Use it sparingly, and prefer an explicit factory function when you can.
Constructors cannot be async
A constructor can't be marked async, and it shouldn't return a promise either. Returning a promise follows the object-return rule, so new would give back the promise instead of an instance. When setup needs asynchronous work, do that work first and pass the results to a constructor that stays synchronous.
class Profile {
constructor(data) {
this.name = data.name;
this.email = data.email;
}
}
async function loadProfile(fetchData) {
const data = await fetchData();
return new Profile(data);
}
loadProfile(async () => ({ name: 'Ada', email: '[email protected]' }))
.then((p) => console.log(p.name)); // 'Ada'A later chapter shows how to attach such factories to the class itself as static methods.
The constructor property
Every instance can reach the class that built it through the constructor property, which it inherits from the prototype.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);
console.log(p.constructor === Point); // true
const copy = new p.constructor(p.x, p.y);
console.log(copy.x, copy.y, copy === p); // 1 2 falsenew p.constructor(...) is handy for writing code that clones an object without knowing its class. Don't rely on it as a type check, because any code can reassign constructor.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Instance properties are missing | You wrote `x = x;` instead of `this.x = x;` | Assign to `this` |
| Constructor code never runs | The method name is misspelled (`constuctor`), so it became an ordinary method and the default constructor ran | Spell it `constructor` |
| `SyntaxError: A class may only have one constructor` | You tried to overload the constructor | Merge them into one constructor that branches on its arguments |
| `TypeError` when an options argument is left out | The destructured parameter has no `= {}` default | Add `= {}` |
| Instances unexpectedly share data | A mutable argument was stored by reference | Copy it in the constructor |
| `new` returns a promise | The constructor returned one, which counts as an object | Use an async factory function |
Exercise
What does this code print, and why? class Box { constructor(v) { this.v = v; return { v: v * 2 }; } } const b = new Box(5); console.log(b.v, b instanceof Box);
Show answer
It prints "10 false". The constructor returns an object, so new discards the instance it built and produces the object literal instead. That literal is a plain object that is not linked to Box.prototype, so instanceof Box is false.
Exercise
Write a Temperature class whose constructor takes celsius (default 0). It should throw a RangeError if the value is below -273.15 and a TypeError if the value is not a finite number. Store the value as this.celsius.
Show answer
class Temperature { constructor(celsius = 0) { if (typeof celsius !== 'number' || !Number.isFinite(celsius)) { throw new TypeError('celsius must be a finite number'); } if (celsius < -273.15) { throw new RangeError('below absolute zero'); } this.celsius = celsius; } } Check the type first, so that values like NaN and strings get the TypeError and never reach the range comparison.
Exercise
A teammate writes class Logger { constuctor(prefix) { this.prefix = prefix; } } and finds that new Logger('app').prefix is undefined. Explain the cause.
Show answer
"constuctor" is misspelled, so it is an ordinary method that nobody calls. The class falls back to the empty default constructor, which never sets prefix. Rename the method to constructor.