Facebook Pixel

Prototype: Real-World Examples in JavaScript

How prototypes are used in real JavaScript applications.

Prototype: Real-World Examples

1. Array Methods

All arrays inherit from Array.prototype:

const arr = [1, 2, 3]; arr.map(fn); // from Array.prototype arr.filter(fn); // from Array.prototype

2. Custom Classes

class ApiClient { constructor(baseUrl) { this.baseUrl = baseUrl; } async get(path) { return fetch(this.baseUrl + path).then(r => r.json()); } } const api = new ApiClient("https://api.example.com"); api.get("/users"); // inherited from ApiClient.prototype

3. Object.create for Prototypal Inheritance

const eventEmitter = { events: {}, on(event, cb) { (this.events[event] ||= []).push(cb); }, emit(event, data) { (this.events[event] || []).forEach(cb => cb(data)); }, }; const myEmitter = Object.create(eventEmitter); myEmitter.on("click", () => console.log("clicked")); myEmitter.emit("click", {});

4. Mixins (Composition)

const Serializable = { toJSON() { return JSON.stringify(this); }, fromJSON(json) { return Object.assign(Object.create(this), JSON.parse(json)); }, }; Object.assign(User.prototype, Serializable);

The Takeaway

Real-world: array methods (all inherit from Array.prototype), custom classes (methods on the prototype), Object.create (prototypal inheritance for event emitters), and mixins (composition by assigning methods to a prototype). Prototypes are the foundation of JS object-oriented programming.

All arrays inherit from Array.prototype. When you call arr.map(fn), JS looks for map on arr, doesn't find it, then finds it on Array.prototype. This is how all arrays share the same methods (map, filter, reduce, etc.).

const child = Object.create(parent). child inherits all properties from parent. This is direct object-to-object inheritance without constructors or classes. Useful for simple prototypal patterns.

A mixin is an object with methods that can be mixed into other objects: Object.assign(MyClass.prototype, SerializableMixin). This adds the mixin's methods to the class's prototype. It is composition over inheritance.

class ApiClient { get(path) {} } puts get on ApiClient.prototype. All instances (new ApiClient()) inherit get from the prototype. This is memory-efficient: one get function shared by all instances.

Memory efficiency. Methods on the prototype are shared by all instances. 1000 instances share 1 method. If methods were on each instance (this.method = function() {}), 1000 instances would have 1000 copies of the method.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.