Glossary / Constructor functions

Constructor functions

A constructor function is a function intended to initialize an object when invoked with new. Before class syntax, this was the standard way to build instance-oriented APIs. The constructor initializes per-instance state; shared methods are usually placed on its .prototype object so instances reuse one function rather than allocate copies.

What new does

function User(name) {
  this.name = name;
}
User.prototype.greet = function () { return `Hi ${this.name}`; };

const ada = new User("Ada");
ada.greet(); // "Hi Ada"

Conceptually, new User(...) creates a fresh object, links its internal prototype to User.prototype, calls User with that object as this, and returns the instance. If the constructor explicitly returns an object, that object is returned instead; primitive returns are ignored. The function’s .prototype property is used for instance links but is not itself the function’s [[Prototype]].

Traditional functions can be called without new, which may cause errors or mutate a global receiver in sloppy mode. Classes reject calls without new. Arrow functions are not constructable. new.target lets a constructor detect construction and can support abstract base patterns, but factories are often clearer.

Modern use

Class syntax is preferred for many new APIs, but recognizing constructor functions remains important in libraries and older code. Avoid per-instance methods when shared behavior belongs on the prototype. Validate constructor arguments and establish invariants consistently; partially initialized instances are a common failure mode.

Interview questions

  1. Where should shared instance methods go? On the constructor’s prototype.
  2. What does new do? Allocate, link prototype, invoke constructor, and choose the result.
  3. What if a constructor returns an object? That object replaces the allocated instance.
  4. Can an arrow function be constructed? No.

References