Sub topic 2
Constructors and Creating Instances with new
This chapter assumes you can declare a class and that you know the basics of functions, objects, and the this keyword. Here you will learn what the constructor method does and what happens, step by step, when you write new.
The constructor method
The constructor is a special method that runs once each time a new instance is created. It usually takes arguments and stores them on this, which refers to the object being built.
class Point {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
const origin = new Point();
const p = new Point(3, 4);
console.log(origin); // Point { x: 0, y: 0 }
console.log(p.x, p.y); // 3 4Constructor parameters work like ordinary function parameters. Default values, destructuring, and rest parameters all work. Each call to new Point(...) produces a separate object with its own x and y.
A class can have only one constructor. If you declare two, you get a SyntaxError. If you leave the constructor out, JavaScript supplies an empty one, constructor() {}, so new still works.
What new does
When you write new Point(3, 4), the engine performs four steps:
- It creates a new, empty object.
- It links that object to
Point.prototype, which is where shared methods live. A later chapter covers this link. - It runs the constructor with
thisset to the new object. - It returns the new object, unless the constructor explicitly returns a different object.
Validating input in the constructor
The constructor is the natural place to reject bad arguments. If it throws, new produces no instance.
class Temperature {
constructor(celsius) {
if (typeof celsius !== 'number' || Number.isNaN(celsius)) {
throw new TypeError('celsius must be a number');
}
this.celsius = celsius;
}
}
console.log(new Temperature(21).celsius); // 21
try {
new Temperature('warm');
} catch (err) {
console.log(err.message); // 'celsius must be a number'
}Common errors
| Mistake | Result |
|---|---|
| Calling `Point(1, 2)` without `new` | `TypeError`: class constructors cannot be invoked without `new` |
| Forgetting `this.` (writing `x = x;`) | The value is assigned to the parameter, not the instance. The property stays missing. |
| Declaring two constructors to "overload" | `SyntaxError`. Use default or optional parameters instead. |
| Returning a primitive such as `return 42;` | The return value is ignored and the instance is returned anyway |
class Weird {
constructor() {
this.a = 1;
return { b: 2 };
}
}
const w = new Weird();
console.log(w); // { b: 2 }
console.log(w instanceof Weird); // falseExercise
Write a class Rectangle whose constructor takes width and height, defaults both to 1, and throws a RangeError if either is negative. What does new Rectangle(5) produce?
Show answer
class Rectangle { constructor(width = 1, height = 1) { if (width < 0 || height < 0) { throw new RangeError('dimensions must be non-negative'); } this.width = width; this.height = height; } } — new Rectangle(5) produces Rectangle { width: 5, height: 1 }, because height falls back to its default.
Exercise
A constructor ends with return 'done';. What does new give you, and why?
Show answer
It gives you the newly created instance. new ignores primitive return values and only replaces the instance when the constructor returns an object.