JavaScript - Prototypes & Native Prototypes
Overview
Estimated time: 35–45 minutes
JavaScript uses prototypes for inheritance. Objects delegate to their prototype via the internal [[Prototype]]
link.
Learning Objectives
- Inspect and modify an object's prototype.
- Understand how
new
links an instance toFunction.prototype
. - Know when not to modify native prototypes.
Prerequisites
Inspecting the prototype
const o = { x: 1 };
const p = Object.getPrototypeOf(o); // usually Object.prototype
Object.setPrototypeOf(o, { y: 2 }); // change prototype (avoid in hot paths)
Functions and prototypes
function Point(x, y) {
this.x = x; this.y = y;
}
Point.prototype.len = function(){ return Math.hypot(this.x, this.y); };
const p1 = new Point(3,4);
p1.len(); // 5
Native prototypes
Array.prototype.first = function(){ return this[0]; };
[10,20].first(); // 10
While possible, modifying native prototypes can break assumptions and cause conflicts. Prefer utility functions or subclass (with care).
Common Pitfalls
- Changing prototypes of many objects at runtime deoptimizes engines.
- Monkey-patching native prototypes risks collisions and surprising behavior.