← Back to Engine

Prototypes & Inheritance


JavaScript is a prototype-based language. Objects inherit properties directly from other objects via a dynamic linkage known as the Prototype Chain.

1. prototype vs [[Prototype]] (__proto__)

  • Function.prototype: An object automatically attached to constructors that defines shared methods for instances created via new.
  • [[Prototype]] / __proto__: An internal pointer on every object pointing up to its parent prototype object.

2. Property Delegation Lookup

When reading obj.prop, JS checks obj. If missing, it traverses up __proto__ -> __proto__.__proto__ until it finds the property or hits null (the top of Object.prototype).

3. Security Gotcha: Prototype Pollution

Modifying Object.prototype directly pollutes every object in the application runtime. Avoid unsafe deep merges of unparsed user JSON payloads!


The Challenge: Prototype EventEmitter

Construct an EventEmitter constructor or class where the event registration methods are attached directly to EventEmitter.prototype:

  1. EventEmitter.prototype.on(event, handler): Registers an event listener callback function.
  2. EventEmitter.prototype.emit(event, ...args): Triggers all registered callbacks for event, passing args.