Constructor Functions
A constructor function is a function you call with new to build an object. The new operator creates a fresh object, links it to the function's .prototype, runs the function with this bound to it, and returns it.
Detailed Explanation
Before class existed in ES2015, this was how JavaScript made objects with shared behaviour. It is still worth understanding, because class is built on exactly this machinery, and plenty of production code and every older library uses it directly.
The convention is a function named with a capital letter, User rather than user, because nothing in the language enforces the difference. Any ordinary function can be called with new.
The new operator does four things, in order:
- Create a new empty object.
- Set that object's internal
[[Prototype]]to the function's.prototypeproperty. - Call the function with
thisbound to the new object, passing your arguments. - Return the new object, unless the function explicitly returns an object of its own, in which case that object wins. A returned primitive is ignored.
Step four is an oddity that occasionally gets used deliberately, for instance to return a cached instance instead of a new one.
The division of labour matters. Per-instance state goes inside the function body, assigned to this. Shared behaviour goes on the function's .prototype, so all instances delegate to one copy. Putting methods inside the constructor body works but allocates a new function object for every instance. For a thousand users that is a thousand identical closures held in memory. The same cost applies today to arrow functions used as class fields, so the trade-off is still live: a prototype method is shared, a field-assigned arrow function is per-instance but captures this automatically.
new.target tells a function whether it was called with new. It is undefined for a plain call, which lets a constructor defend itself, and is also how the engine knows a class was called incorrectly.
instanceof works with constructor functions because it walks the prototype chain looking for Constructor.prototype. Inheritance is possible too, but you have to wire it yourself: call the parent with Parent.call(this, ...), set Child.prototype = Object.create(Parent.prototype), and restore Child.prototype.constructor. Forgetting the last step breaks instance.constructor. This boilerplate is the main reason class was added.
When should you write one today? Rarely. Use class for new code: it is shorter, it makes the intent obvious, it supports #private fields, and it refuses to run without new. Constructor functions remain relevant for reading existing code, for interview questions, and for the occasional case where you want a callable-and-constructable function or need to avoid class semantics such as the strict-mode class body.
The real cost of the older form is the failure mode. A constructor function called without new does not throw. In strict mode this is undefined, so the first assignment throws a confusing TypeError; in sloppy mode this is the global object and your properties get silently attached to it. Classes turned that whole category of bug into an immediate, clear error.
Code Examples
function User(email, role) {
// `this` is the brand-new object that `new` created.
this.email = email;
this.role = role;
}
// Shared across every instance: one function object, not one per user.
User.prototype.describe = function () {
return `${this.email} (${this.role})`;
};
const ada = new User("ada@example.com", "engineer");
console.log(ada.describe()); // => ada@example.com (engineer)
console.log(ada instanceof User); // => true
console.log(Object.getPrototypeOf(ada) === User.prototype); // => true
// The method is shared, so both instances point at the identical function.
const grace = new User("grace@example.com", "admin");
console.log(ada.describe === grace.describe); // => true
// new.target distinguishes `new User(...)` from `User(...)`.
function SafeUser(email) {
if (new.target === undefined) {
throw new TypeError("SafeUser must be called with new");
}
this.email = email;
}
try {
SafeUser("oops"); // no `new`
} catch (err) {
console.log(err.message); // => SafeUser must be called with new
}"use strict";
// Inheritance before `class`: three manual steps.
function Account(owner) {
this.owner = owner;
this.balance = 0;
}
Account.prototype.summary = function () {
return `${this.owner}: ${this.balance}`;
};
function SavingsAccount(owner, rate) {
Account.call(this, owner); // 1. run the parent's initialisation on `this`
this.rate = rate;
}
// 2. link the prototypes so instances inherit summary()
SavingsAccount.prototype = Object.create(Account.prototype);
// 3. repair the constructor pointer that step 2 overwrote
SavingsAccount.prototype.constructor = SavingsAccount;
SavingsAccount.prototype.summary = function () {
// Call the shadowed parent method explicitly; there is no `super` here.
return `${Account.prototype.summary.call(this)} @ ${this.rate}%`;
};
const s = new SavingsAccount("Ada", 4.5);
s.balance = 100;
console.log(s.summary()); // => Ada: 100 @ 4.5%
console.log(s instanceof Account); // => true
console.log(s.constructor.name); // => SavingsAccount
// The equivalent today is four lines of `class` with `extends` and `super`.Common Gotchas
Forgetting `new` fails in a confusing way
in strict mode `this` is `undefined` and the first property assignment throws `TypeError: Cannot set properties of undefined`. In sloppy mode there is no error at all: the properties land on the global object and the call returns `undefined`, so the caller gets a broken variable. Guard with `new.target`, or use `class`, which throws immediately.
Replacing `.prototype` wipes the `constructor` property
after `Child.prototype = Object.create(Parent.prototype)`, `instance.constructor` reports `Parent` until you reassign it. Restore it, and prefer adding to the existing prototype object over replacing it, since objects created earlier keep the old link.
Methods defined inside the constructor body cost memory
each instance gets its own function object rather than sharing one. With many instances this is real heap usage. Put methods on the prototype unless you specifically need the per-instance `this` binding that an arrow function field provides.
An explicit object return overrides the new instance
`return someObject` from a constructor makes `new Fn()` evaluate to `someObject`. Returning a primitive is ignored and the instance is returned as usual. This is occasionally used to return cached or pooled objects.