What Are JavaScript Prototypes?
JavaScript is a prototype-based language, meaning objects can inherit properties and methods from other objects. Unlike classical inheritance (used in Java or C++), JavaScript relies on prototypes for object-oriented programming.
How Prototypes Work in JavaScript
Every JavaScript object has a hidden [[Prototype]]
property that links to another object (its prototype). When you access a property or method, JavaScript checks:
- The object itself.
- Its prototype (if not found).
- The prototype’s prototype (forming a prototype chain) until it reaches
null
.
Example: Prototype Inheritance
function Person(name) {
this.name = name;
}
// Adding a method to the prototype
Person.prototype.greet = function() {
return `Hello, ${this.name}!`;
};
const john = new Person("John");
console.log(john.greet()); // "Hello, John!"
Here, john
inherits greet()
from Person.prototype
.
Why Prototypes Matter
- Memory Efficiency – Methods defined on prototypes are shared across instances.
- Dynamic Updates – Changing a prototype affects all instances.
- Flexible Inheritance – Objects can inherit from multiple prototypes.
Common Prototype Methods
Object.create()
– Creates a new object with a specified prototype.
Object.getPrototypeOf()
– Returns an object’s prototype.
instanceof
– Checks if an object inherits from a prototype.
Modern JavaScript: Classes vs. Prototypes
ES6 introduced class
, but it’s syntactic sugar over prototypes:
class Person {
constructor(name) { this.name = name; }
greet() { return `Hello, ${this.name}!`; }
}
Under the hood, it still uses prototypes.
Key Takeaways
- JavaScript uses prototypal inheritance (not classical).
- The
prototype
property allows method sharing.
__proto__
(deprecated) and Object.getPrototypeOf()
access prototypes.
- ES6 classes simplify prototype syntax but work the same way.