How do you write a constructor function?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
A constructor is an ordinary function you call with new. Convention capitalises the name so readers know it is meant to be used that way — JavaScript itself does not enforce it.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const p = new Person("Mai", 30);
p.greet(); // "Hi, I'm Mai"
Methods go on prototype, not inside the constructor. Defining this.greet = function... would create a separate copy for every instance; on the prototype there is one copy shared by all of them.
What new does
Four steps: create an empty object, set its prototype to Person.prototype, run the function with this bound to that object, and return it automatically unless the function returns a different object explicitly.
The trap
Forgetting new fails quietly:
const bad = Person("Mai", 30); // undefined, and `this` was undefined inside
In strict mode or a module, this.name = name throws; in sloppy mode it writes to the global object instead. You can guard against it:
function Person(name) {
if (!new.target) return new Person(name);
this.name = name;
}
Prefer class in new code
class Person {
constructor(name) { this.name = name; }
greet() { return `Hi, I'm ${this.name}`; }
}
This is the same prototype machinery with clearer syntax, and it removes the trap above — calling a class without new throws a TypeError immediately. It also gives you extends, super and private #fields. Constructor functions are still worth understanding, because that is what you will meet in older code and what class compiles down to conceptually.
