Sub topic 4
What Classes Really Are: Functions and Prototypes
This chapter assumes you can already declare a class, write a constructor, and add instance methods, all covered in earlier chapters. It also assumes you know plain JavaScript objects and functions, and that this refers to the object a method is called on. The goal here is to show what the engine builds when it evaluates a class declaration. With that picture, you can predict how lookups, overrides, and patches behave, and you can debug output from console.log and Object.keys that otherwise looks surprising.
A Class Is a Function
A class declaration creates a function. The function body is the constructor. Every other method you write in the class body goes on an object stored in the function's prototype property.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const p = new Point(1, 2);
console.log(typeof Point); // "function"
console.log(Object.getPrototypeOf(p) === Point.prototype); // true
console.log(Object.hasOwn(p, 'distanceTo')); // false
console.log(Object.hasOwn(Point.prototype, 'distanceTo')); // trueThese four lines give the whole model:
Pointis a function object.Point.prototypeis an ordinary object created along with the class.- Each instance has an internal link, called
[[Prototype]], that points toPoint.prototype.Object.getPrototypeOfreads that link. distanceTois not stored onp. It lives once onPoint.prototype.
The name of the prototype property is easy to misread. Point.prototype is not the prototype of Point. It is the object that will become the prototype of instances created by new Point(). The prototype of the function Point itself is Function.prototype.
class Point {}
console.log(Object.getPrototypeOf(Point) === Function.prototype); // true
console.log(Object.getPrototypeOf(new Point()) === Point.prototype); // trueOwn Properties vs. Inherited Properties
Properties assigned to this in the constructor are own properties: they are stored directly on the instance. Methods are inherited properties: the instance finds them by following its [[Prototype]] link.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const a = new Point(0, 0);
const b = new Point(3, 4);
console.log(Object.keys(a)); // [ 'x', 'y' ]
console.log(Object.getOwnPropertyNames(Point.prototype)); // [ 'constructor', 'distanceTo' ]
console.log(a.distanceTo === b.distanceTo); // true
console.log(Point.prototype.constructor === Point); // trueBoth instances share one distanceTo function. A thousand points cost a thousand x/y pairs and still only one copy of the method. The constructor property on the prototype points back to the class, which is how a.constructor === Point works.
How Property Lookup Walks the Chain
When you read a.distanceTo, the engine runs these steps:
- Look for an own property named
distanceToona. None is found. - Follow
a's[[Prototype]]toPoint.prototype.distanceTois found there and returned. - If it were still missing, the engine would follow
Point.prototype's own[[Prototype]], which isObject.prototype, and thennull, where lookup stops and returnsundefined.
This linked sequence of objects is the prototype chain. It is also why a.toString() and a.hasOwnProperty('x') work even though Point never defined them: they come from Object.prototype.
class Point {}
const p = new Point();
console.log(Object.getPrototypeOf(Point.prototype) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // nullThe this value inside an inherited method is still the object you called it on. When you call a.distanceTo(b), the function is found on Point.prototype, but this is a. That is how one shared function can read different x and y values for each instance.
What `new` Does
Calling new Point(1, 2) performs these steps:
- Create a new empty object whose
[[Prototype]]isPoint.prototype. - Run the constructor body with
thisbound to that object. - Return the object, unless the constructor explicitly returns a different object.
You can reproduce this by hand with a plain constructor function. You cannot do it with a class, because a class refuses to be called without new. The next chapter covers that rule.
function PointFn(x, y) {
this.x = x;
this.y = y;
}
const manual = Object.create(PointFn.prototype); // step 1
PointFn.call(manual, 1, 2); // step 2
console.log(manual.x, manual.y); // 1 2
console.log(manual instanceof PointFn); // trueThe Pre-Class Equivalent
Before ES2015, developers wrote the same structure by hand. This version builds roughly the same objects as the Point class:
function PointFn(x, y) {
this.x = x;
this.y = y;
}
PointFn.prototype.distanceTo = function (other) {
return Math.hypot(this.x - other.x, this.y - other.y);
};
const q = new PointFn(0, 0);
console.log(q.distanceTo(new PointFn(3, 4))); // 5
console.log(Object.getPrototypeOf(q) === PointFn.prototype); // trueClasses are often called "syntactic sugar" for this pattern. That is mostly accurate for the structure, but the details differ in ways you can observe:
| Behavior | `class` | Constructor function |
|---|---|---|
| Methods enumerable in `for...in` | No | Yes, when assigned with `=` |
| Callable without `new` | No, throws `TypeError` | Yes, `this` becomes the global object or `undefined` |
| Body runs in strict mode | Always | Only with `'use strict'` |
| `Fn.prototype` can be reassigned | No, it is non-writable | Yes |
| Hoisting | Temporal dead zone | Fully hoisted |
The enumerability difference matters in practice:
class A {
m() {}
}
function B() {}
B.prototype.m = function () {};
for (const key in new A()) console.log('A:', key); // prints nothing
for (const key in new B()) console.log('B:', key); // B: m
console.log(Object.getOwnPropertyDescriptor(A.prototype, 'm').enumerable); // falsefor...in visits enumerable properties along the entire chain, not just own properties. Class methods are created non-enumerable, so they stay out of loops and out of most generic object-copying code. The strict-mode, new, and hoisting rows are the subject of the next chapter.
Consequences You Will Run Into
Shadowing a Method on One Instance
Assigning to a property always creates or updates an own property on the target object. It never writes through to the prototype. An own property with the same name as an inherited one shadows it, which means lookup stops at the instance and never reaches the prototype.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
describe() { return `(${this.x}, ${this.y})`; }
}
const a = new Point(1, 2);
const b = new Point(3, 4);
a.describe = () => 'custom';
console.log(a.describe()); // 'custom'
console.log(b.describe()); // '(3, 4)'
delete a.describe;
console.log(a.describe()); // '(1, 2)', the prototype method is visible againPatching the Prototype Affects Every Instance
Instances hold a live link, not a copy. If you add or replace a method on Point.prototype, every existing instance sees the change right away:
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
const a = new Point(1, 2);
Point.prototype.toString = function () {
return `Point(${this.x}, ${this.y})`;
};
console.log(`${a}`); // 'Point(1, 2)'Debugging Output Hides Inherited Members
Object.keys, JSON.stringify, and object spread ({ ...a }) look only at own enumerable properties. A spread copy of a Point is a plain object with x and y and no distanceTo:
class Point {
constructor(x, y) { this.x = x; this.y = y; }
distanceTo(o) { return Math.hypot(this.x - o.x, this.y - o.y); }
}
const copy = { ...new Point(1, 2) };
console.log(copy); // { x: 1, y: 2 }
console.log(typeof copy.distanceTo); // 'undefined'
console.log(copy instanceof Point); // falseTo clone an instance and keep its methods, preserve the prototype link: Object.assign(Object.create(Object.getPrototypeOf(a)), a).
Exercises
Exercise
Given class Cat { meow() { return 'meow'; } } and const c = new Cat();, what do Object.hasOwn(c, 'meow'), 'meow' in c, and Object.keys(Cat.prototype) return, and why?
Show answer
false, true, and []. meow is stored on Cat.prototype, not on c, so hasOwn is false. The in operator searches the whole prototype chain, so it finds meow. Object.keys lists only enumerable own properties, and class methods are non-enumerable, so the array is empty.
Exercise
You create two instances x and y of a class Timer, then run x.start = () => 'patched' and Timer.prototype.stop = () => 'stopped'. Which instances see the patched start, and which can call stop?
Show answer
Only x sees the patched start, because the assignment created an own property on x that shadows the prototype method. Both x and y can call stop, because it was added to the shared prototype that both instances link to.
Exercise
Rewrite class Greeter { constructor(name) { this.name = name; } greet() { return 'Hi ' + this.name; } } as a constructor function with a prototype method. Then name one behavior your version has that the class does not.
Show answer
function Greeter(name) { this.name = name; } Greeter.prototype.greet = function () { return 'Hi ' + this.name; }; Any one of these differences is correct: greet is enumerable and appears in for...in loops; Greeter('Ann') can be called without new and does not throw; Greeter.prototype can be reassigned; the function is fully hoisted.