In JavaScript, prototypes are a fundamental feature that enables object inheritance. Every JavaScript object has a built-in property called prototype
, which allows one object to inherit properties and methods from another. This prototype mechanism forms the backbone of JavaScript’s object-oriented programming model.
What Is a Prototype?
- A prototype is an object associated with another object or function.
- When you access a property or method on an object, JavaScript first looks for it in the object itself. If it doesn’t find it, the search moves to the object’s prototype.
Example:
const person = {
greet: function() {
console.log("Hello!");
}
};
const john = Object.create(person); // Creates an object inheriting from 'person'
john.greet(); // Output: Hello!
In this example, john
does not have its own greet
method, so JavaScript uses the method from its prototype, person
.
Prototype Chain
JavaScript objects are linked via a prototype chain:
- When a property is accessed, the interpreter searches for it in the object, then in its prototype, and so on up the chain until it reaches
null
(the end of the chain).
Visualization:
const obj = {};
console.log(obj.toString()); // 'toString' comes from Object.prototype
Here, toString
is not defined on obj
but is found on Object.prototype
.
Modifying Prototypes
Prototypes can be extended to add shared methods or properties to all objects created from a constructor.
Example:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
const dog = new Animal("Dog");
dog.speak(); // Output: Dog makes a noise.
Prototype vs __proto__
vs Object.getPrototypeOf
- Prototype: Refers to the property available on functions (e.g.,
Function.prototype
). __proto__
: Refers to the prototype object of an instance.Object.getPrototypeOf(obj)
: Preferred way to access the prototype of an object in modern JavaScript.
Real-World Applications
- Inheritance: Implement common behaviors like
Array.prototype.map
. - Memory Efficiency: Shared methods on prototypes save memory compared to duplicating methods in each instance.
- Frameworks: Many libraries use prototypes for reusable components.
Conclusion
Understanding prototypes is crucial for mastering JavaScript. They provide a powerful way to implement inheritance, enhance objects, and create scalable code. For more hands-on tutorials and advanced topics, visit The Coding College.