Constructor functions and new
Before classes, JavaScript made objects with a function and the new keyword. The function writes fields on this, and new supplies the object, links it to the prototype of the function and returns it. It is the same operation a class performs, with no syntax of its own.
This lesson reads that operation apart: what new does, why a method belongs on the prototype rather than in the function, what happens when the keyword is missing, and how instanceof follows the chain. The lesson on this covers the other ways a call can set it.
new and this
A call with new makes a fresh object, sets its prototype to Point.prototype, runs the function with that object as this, and returns it unless the function returns an object of its own. The function is called a constructor by convention and its name is capitalised, which is a signal to the reader and nothing more.
The file new.mjs:
function Point(x, y) {
this.x = x;
this.y = y;
}
const p = new Point(3, 4);
console.log('the fields:', p.x, p.y);
console.log('the type is still object:', typeof p);
console.log('its constructor is the function:', p.constructor === Point);
console.log('it is an instance:', p instanceof Point);
const q = new Point(10, 20);
console.log('a second call makes another object:', p !== q);
console.log('and its fields belong to it:', q.x, q.y);
node new.mjs
the fields: 3 4
the type is still object: object
its constructor is the function: true
it is an instance: true
a second call makes another object: true
and its fields belong to it: 10 20
The two fields belong to the instance, the type of the value is still
object, and the constructor property points back at the function through the prototype. The second call made a second object with its own fields, so nothing is shared except the link. Every one of those facts comes from the four steps of new.
A method on the prototype
A method written inside the constructor would be created again for every instance, which costs memory and makes two instances disagree about what their method is. A method on Point.prototype is created once, and every instance reads it through the chain. The two instances then hold the same function in their distance property, and neither owns it.
The file shared.mjs:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.distance = function distance() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
const a = new Point(3, 4);
const b = new Point(6, 8);
console.log('the distance of a:', a.distance());
console.log('the distance of b:', b.distance());
console.log('one function for both:', a.distance === b.distance);
console.log('the method is not an own key:', Object.hasOwn(a, 'distance'));
console.log('the own keys are the fields:', Object.keys(a).join(','));
console.log('the method lives on the prototype:', Object.hasOwn(Point.prototype, 'distance'));
node shared.mjs
the distance of a: 5
the distance of b: 10
one function for both: true
the method is not an own key: false
the own keys are the fields: x,y
the method lives on the prototype: true
Two distances from one function, and the identity check proves there is one. The list of own keys holds the two fields and not the method, which is the difference that matters for copying and for JSON. The last line reads the prototype of the constructor directly, and the method is its own property there.
The call that forgot new
A constructor is an ordinary function, so it can be called without new, and then there is no object to write to: in strict code this is undefined and the first write throws. In sloppy code this would be the global object, and the fields would land there in silence, which is the worse failure of the two.
The file forgotten.mjs:
function Point(x, y) {
this.x = x;
this.y = y;
}
try {
Point(1, 2);
} catch (error) {
console.log('without new:', error.name + ': ' + error.message);
}
const made = new Point(1, 2);
console.log('with new:', made.x, made.y);
function Bag() {
this.items = [];
return { replaced: true };
}
console.log('a returned object wins:', JSON.stringify(new Bag()));
node forgotten.mjs
without new: TypeError: Cannot set properties of undefined (setting 'x')
with new: 1 2
a returned object wins: {"replaced":true}
The error names the property and the value it tried to write it on, and the call with the keyword works as before. The last two lines are a detail of the fourth step of new: a function that returns an object replaces the fresh one, which is why a constructor should return nothing. A class refuses the call without the keyword outright, which is one of the things the next lesson adds.
instanceof and the chain
instanceof asks whether the prototype of a constructor is anywhere in the chain of an object, so an instance of a derived constructor is an instance of both. The derived constructor here calls the parent with Shape.call(this, ...), which runs the parent body on the same object, and then sets the prototype of its own prototype object to the parent prototype. That handwork is exactly what extends writes for you.
The file instanceof.mjs:
function Shape(kind) {
this.kind = kind;
}
Shape.prototype.describe = function describe() {
return `a ${this.kind}`;
};
function Square(size) {
Shape.call(this, 'square');
this.size = size;
}
Square.prototype = Object.create(Shape.prototype);
Square.prototype.constructor = Square;
const s = new Square(3);
console.log('the inherited method:', s.describe());
console.log('a square is both:', s instanceof Square, s instanceof Shape);
console.log('its constructor is Square again:', s.constructor === Square);
console.log('the chain holds:', Object.getPrototypeOf(s) === Square.prototype);
console.log('the inherited field came through call:', s.kind);
node instanceof.mjs
the inherited method: a square
a square is both: true true
its constructor is Square again: true
the chain holds: true
the inherited field came through call: square
The square answered to both names and kept the parent method through the chain. The constructor property was overwritten on purpose, because the object created by Object.create would otherwise point at the parent. Three lines of setup and one call are a lot to remember, which is the argument for the class syntax of the next lesson rather than against prototypes.
Exercises
- Print Object.getPrototypeOf(p) in new.mjs. Which object does it show, and what is on it?
- Move distance into the constructor body in shared.mjs and compare two instances again. Which of the two identity lines changes?
- Call Point(1, 2) in forgotten.mjs from a file with no strict mode, such as a .cjs file. What does the program print instead of the error?
- Add a third class that extends Square in instanceof.mjs with the same handwork. How many lines of setup does it take, and what does instanceof Shape answer?
- Write a constructor that returns a number, and then one that returns an object. Which of the two return values reaches the caller?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does new do before the constructor body runs?
Answer
It creates an object and links it to the prototype of the function
The fresh object is what this is inside the call, and its prototype is the one of the function.
-
Why is a method put on
Point.prototypeinstead of in the constructor?Answer
One function is shared by every instance
A method in the body is created per instance, while the prototype holds one copy.
-
What happens when a constructor is called without new in a module?
Answer
this is undefined and the first write throws a TypeError
A module is strict code, so this is undefined and there is nothing to write the fields on.
-
What does
dog instanceof Animalask?Answer
Whether Animal.prototype is in the chain of dog
The operator walks the chain and looks for the prototype of the constructor.
-
What does this program print?
function Point(x) { this.x = x; } const p = new Point(3); console.log(p.x, typeof p);Answer
3 object
The field was written on the fresh object, and the value that comes back is that object.
-
What does this program print?
function P() {} P.prototype.kind = "p"; const a = new P(); const b = new P(); console.log(a.kind, a.kind === b.kind);Answer
p true
Both instances read the same inherited value from the one prototype.
-
What does this program print?
function P() {} P.prototype.go = function () { return "go"; }; const a = new P(); console.log(Object.keys(a).length);Answer
0
The method is on the prototype, so the instance owns no keys at all.
-
What does this program print?
function Shape() {} function Square() { Shape.call(this); } Square.prototype = Object.create(Shape.prototype); console.log(new Square() instanceof Shape);Answer
true
The prototype of the square prototype is the shape prototype, so the chain reaches it.
-
What happens when this module runs?
function Point(x) { this.x = x; } Point(1);Answer
It throws a TypeError, because this is undefined
There is no object without new, and strict code does not fall back to the global object.
-
What does this program print?
function Bag() { this.items = []; return { done: true }; } console.log(JSON.stringify(new Bag()));Answer
{"done":true}
A constructor that returns an object hands that object back instead of the fresh one.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev