Prototype
An object in JavaScript that allows objects to inherit properties and methods from other objects, forming the basis of JavaScript's inheritance model.
Overview
Every JavaScript object has a prototype, which is another object from which it inherits properties and methods. This prototypal inheritance allows objects to share functionality without duplicating code. It's different from classical inheritance found in languages like Java or C++.
Example
javascript// Constructor function function Person(name) { this.name = name; } // Add method to prototype Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); const bob = new Person('Bob'); alice.greet(); // "Hello, I'm Alice" bob.greet(); // "Hello, I'm Bob" // Both share the same greet method alice.greet === bob.greet; // true
Key Points
- Every object has a prototype (except Object.prototype)
- Enables inheritance and method sharing
- Accessed via proto or Object.getPrototypeOf()
- Methods on prototype are shared across instances
- Modern approach: use class syntax
Learn More
- Class - ES6 classes
- Object - JavaScript objects
- MDN: Prototypes