JavaScript is a prototype-based language, which means objects can serve as prototypes for other objects. Each object in JavaScript has a prototype, and it inherits properties and methods from that prototype.
Object Prototype
Every object in JavaScript is linked to a prototype object. When you create an object, JavaScript automatically attaches a special property called proto to it, pointing to its prototype.
const myObject = {};
console.log(myObject.__proto__); // Outputs the prototype of myObject
Prototype Chain
Objects in JavaScript form a chain, known as the prototype chain. If a property or method is not found on an object, JavaScript looks up the prototype chain until it finds the property or reaches the end of the chain (usually the Object prototype).
Creating objects with prototypes
// Creating a prototype object
const animalPrototype = {
speak: function() {
console.log("Some generic sound");
}
};
// Creating an object using the prototype
const dog = Object.create(animalPrototype);
dog.speak(); // Outputs "Some generic sound"
In this example, dog is created with animalPrototype as its prototype. It inherits the speak method from animalPrototype.
Constructor Functions:
// Constructor function
function Animal() {}
// Adding a method to the prototype of the constructor
Animal.prototype.speak = function() {
console.log("Some generic sound");
};
// Creating an instance
const cat = new Animal();
cat.speak(); // Outputs "Some generic sound"
Here, Animal is a constructor function, and instances created with new Animal() inherit from Animal.prototype.
Prototypal inheritance is a fundamental concept in JavaScript that allows objects to inherit properties and methods from other objects. Here's a breakdown :
- Prototype: Think of a prototype as a blueprint for creating objects. Every object has a prototype, and it serves as a template for the object's properties and methods.
- Prototype Chain: Objects are linked together in a chain, forming the prototype chain. If a property or method is not found on an object, JavaScript looks up the chain until it finds the property or reaches the end.
- Creating Objects with Prototypes: You can create objects directly using Object.create(prototype) or use constructor functions. Objects created with the same prototype share common functionality.
- Constructor Functions: Constructor functions are a way to create objects with a shared prototype. They serve as a template for creating multiple instances with similar properties and methods.
Top comments (0)