JavaScript Prototypes and Constructor Functions: How Classes Work Underneath
What a "class" really is in JavaScript: objects sharing a prototype. Factory functions with Object.create, constructor functions and new, the prototype and constructor properties, how instanceof and isPrototypeOf work, why methods belong on the prototype, and adding methods to existing classes.
kvi5hnuCode Sprout team member7 min readOn this page
Most programs deal with many objects of the same kind: users, products, points, temperatures. Each has its own data but the same behavior. A class describes that kind of object once: what data each instance holds and which methods they all share.
JavaScript has a class keyword (next article), but it's a newer syntax for a mechanism that's been in the language from the start: prototypes. Understanding that mechanism explains how classes really behave, how instanceof works, and what old code (and transpiled code) is doing. If you come from Java or C#, note that JavaScript classes look similar but work quite differently underneath.
A class is a shared prototype
Article 46 showed that every object has a prototype and inherits its properties. In JavaScript, a class is a set of objects that inherit from the same prototype object. The prototype holds the shared methods; each instance holds its own data.
The simplest way to build that by hand is a factory function with Object.create:
const temperatureMethods = {
toFahrenheit() {
return this.celsius * 9 / 5 + 32;
},
describe() {
return `${this.celsius} C`;
},
};
function temperature(celsius) {
const t = Object.create(temperatureMethods); // inherit the shared methods
t.celsius = celsius; // own data
return t;
}
const room = temperature(20);
const body = temperature(37);
console.log(room.toFahrenheit(), body.describe());
console.log(Object.keys(room), room.toFahrenheit === body.toFahrenheit);
68 37 C
[ 'celsius' ] true
Each object stores only celsius; both find toFahrenheit through their prototype, and it's the same function. The methods use this to reach the data of whichever instance they were called on (article 64).
Constructor functions
The traditional way to define a class, before ES2015, is a constructor function called with new. As article 64 explained, new F(...):
- creates a new object whose prototype is
F.prototype, - runs
Fwiththisset to that object, - returns the object.
So the constructor only has to initialize this, and shared methods go on F.prototype:
function Temperature(celsius) {
this.celsius = celsius;
}
Temperature.prototype.toFahrenheit = function () {
return this.celsius * 9 / 5 + 32;
};
Temperature.prototype.describe = function () {
return `${this.celsius} C`;
};
const day = new Temperature(25);
console.log(day.toFahrenheit(), day.describe(), day instanceof Temperature);
console.log(Object.getPrototypeOf(day) === Temperature.prototype);
77 25 C true
true
Conventions: constructor names start with a capital letter (Temperature, Date, Map), which signals "call me with new"; ordinary functions and methods start lowercase. Methods are regular functions, never arrows, because they need their own this.

prototype vs [[Prototype]]
Two different things have confusingly similar names:
F.prototypeis an ordinary property of a function. It's the object that will become the prototype of instances created withnew F().- An object's prototype (internally
[[Prototype]], read withObject.getPrototypeOf(obj)or the legacyobj.__proto__) is the object it inherits from.
So Object.getPrototypeOf(day) === Temperature.prototype, but Temperature.prototype is not the prototype of Temperature itself (that's Function.prototype). Every regular function automatically gets a prototype object; arrow functions and methods don't, which is why they can't be constructors.
Why methods go on the prototype
You could create methods inside the constructor instead:
function PerInstance(celsius) {
this.celsius = celsius;
this.toFahrenheit = function () { // a new function for every object
return this.celsius * 9 / 5 + 32;
};
}
const a = new PerInstance(1);
const b = new PerInstance(2);
console.log(a.toFahrenheit === b.toFahrenheit);
false
That works, but each instance gets its own copy of every method, which wastes memory with many instances and means you can't add or change a method for all instances at once. Prototype methods exist once and are shared. (Closure-based objects, article 67, make the same trade-off in exchange for private variables.)
The constructor property
Every function's automatic prototype object has one property, constructor, pointing back to the function. Instances inherit it, so obj.constructor tells you which constructor made an object:
function Temperature(celsius) {
this.celsius = celsius;
}
const t = new Temperature(10);
console.log(Temperature.prototype.constructor === Temperature, t.constructor === Temperature);
const another = new t.constructor(30); // create a "sibling" without naming the class
console.log(another.celsius);
true true
30
A common mistake in older code is replacing the prototype with an object literal, which loses constructor:
function Broken(v) { this.v = v; }
Broken.prototype = { show() { return this.v; } }; // constructor is gone
console.log(new Broken(1).constructor === Broken, new Broken(1).constructor === Object);
function Fixed(v) { this.v = v; }
Fixed.prototype = { constructor: Fixed, show() { return this.v; } };
console.log(new Fixed(1).constructor === Fixed);
false true
true
Either add constructor back explicitly, or add methods to the existing prototype one at a time (F.prototype.show = function () {...}). The class syntax handles this for you.
instanceof and isPrototypeOf
obj instanceof F checks whether F.prototype appears anywhere in obj's prototype chain. It doesn't check which function actually created the object:
function Temperature(c) { this.celsius = c; }
function Impostor() {}
Impostor.prototype = Temperature.prototype; // share the prototype
const fake = new Impostor();
console.log(fake instanceof Temperature, fake.celsius);
console.log([] instanceof Array, [] instanceof Object, Object.create(null) instanceof Object);
true undefined
true true false
fake counts as a Temperature because it inherits from Temperature.prototype, even though it was never initialized as one. The prototype, not the constructor, defines the class identity.
For classes without a constructor (like the factory version above), test the prototype directly with isPrototypeOf:
const pointMethods = { norm() { return Math.hypot(this.x, this.y); } };
const pt = Object.assign(Object.create(pointMethods), { x: 3, y: 4 });
console.log(pointMethods.isPrototypeOf(pt), pt.norm());
true 5
instanceof also fails across realms (an array from an iframe isn't instanceof this window's Array), which is why Array.isArray exists (article 62). A class can customize instanceof with a static Symbol.hasInstance method (part 14), though that's rarely a good idea.
Duck typing
Because instanceof checks the chain rather than behavior, JavaScript code often uses duck typing instead: "if it walks like a duck and quacks like a duck, treat it as a duck." Instead of asking "is this a Temperature?", ask "does it have what I need?":
function printAll(items) {
for (const item of items) {
console.log(typeof item.describe === "function" ? item.describe() : String(item));
}
}
printAll([{ describe: () => "a custom object" }, 42]);
a custom object
42
Iteration in JavaScript works this way: anything with a Symbol.iterator method is iterable (part 12), whatever its class.
Adding methods to existing classes
Prototypes are live (article 47): adding a method to a prototype makes it available immediately on all instances, including ones created earlier:
function Temperature(c) { this.celsius = c; }
const early = new Temperature(0);
Temperature.prototype.toKelvin = function () {
return this.celsius + 273.15;
};
console.log(early.toKelvin());
273.15
This works for built-in classes too, and it's how polyfills add missing features to older environments: if (!Array.prototype.at) { Array.prototype.at = function (i) {...}; }.
Old-style classes vs the class keyword
Everything here is still exactly how classes work. The class syntax in the next article is a clearer way to write the same thing:
function OldPoint(x, y) { this.x = x; this.y = y; }
OldPoint.prototype.norm = function () { return Math.hypot(this.x, this.y); };
class NewPoint {
constructor(x, y) { this.x = x; this.y = y; }
norm() { return Math.hypot(this.x, this.y); }
}
console.log(new OldPoint(3, 4).norm(), new NewPoint(3, 4).norm());
console.log(typeof NewPoint, Object.getOwnPropertyNames(NewPoint.prototype));
5 5
function [ 'constructor', 'norm' ]
A class is a constructor function, and its methods are properties of its prototype. The class syntax adds some safety (it can't be called without new, its methods are non-enumerable, its body is strict mode) and features like private fields, but the model underneath is the same.
Common questions
Is JavaScript object-oriented if it uses prototypes instead of classes?
Yes. It's object-oriented with prototype-based inheritance: objects inherit directly from other objects. Class-based languages like Java copy behavior from class definitions instead. JavaScript's class syntax provides the familiar look on top of prototypes.
Should I write constructor functions today?
No; use class for new code. Knowing constructor functions helps you read older code, understand transpiler output and libraries, and answer interview questions about prototypes.
What's the difference between __proto__ and prototype?
obj.__proto__ is a legacy accessor for an object's own prototype (use Object.getPrototypeOf instead). F.prototype is a property of a function that becomes the prototype of objects created by new F().
Can a class be defined without any constructor?
Yes. Any group of objects sharing a prototype forms a class. Factory functions with Object.create, as at the start of this article, are a valid style; use isPrototypeOf to test membership.
Summary
- In JavaScript, a class is a set of objects that inherit from the same prototype; the prototype holds shared methods, the instances hold their own data.
- A factory function can build instances with
Object.create(proto). - A constructor function initializes
this;new F()creates objects whose prototype isF.prototype. Capitalize constructor names and never use arrows as constructors or methods. F.prototype(a function property) is different from an object's own prototype (Object.getPrototypeOf(obj)).F.prototype.constructorpoints back toF; replacing the prototype object loses it unless you restore it.instanceofchecks the prototype chain, not who created the object;isPrototypeOftests a prototype directly.- Prototypes are live, so methods added later reach existing instances; don't add your own methods to built-in prototypes.
Practice Questions
What does this print?
function Dog(n) {
this.n = n;
}
Dog.prototype.speak = function () {
return this.n + " barks";
};
const d = new Dog("Rex");
console.log(d.speak(), Object.keys(d), "speak" in d);
Answer
Rex barks [ 'n' ] true. speak is inherited, so it's not an own key, but in finds inherited properties.
After this code, what is new A().constructor?
function A() {};
A.prototype = { hi() {} };
Answer
Object. The replacement prototype has no constructor property, so lookup continues to Object.prototype.constructor.
Write a factory function point(x, y) whose instances share a toString method that returns "(x, y)".
Answer
const pointProto = { toString() { return `(${this.x}, ${this.y})`; } };
Then build each instance on that prototype:
const point = (x, y) => Object.assign(Object.create(pointProto), { x, y });
String(point(1, 2)) gives "(1, 2)".
Why might obj instanceof Temperature be true even though obj.celsius is undefined?
Answer
instanceof only checks whether Temperature.prototype is in obj's prototype chain. An object created with Object.create(Temperature.prototype), or by another constructor sharing that prototype, passes the test without ever running the Temperature constructor.
Next: JavaScript Classes: class Syntax, Constructors, Methods, Fields, Static Members and Private #fields

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.