| Classes-ES6-Javascript | Encapsulation | |
JavaScript Prototypes and Inheritance |
JavaScript, unlike traditional object-oriented languages that use a class-based inheritance model, uses a prototype-based model.
A prototype is a blueprint-like object that other objects can inherit properties and methods from.
Prototype property, which is a link to another object. Prototype . This process continues up the prototype chain until the property is found or the end of the chain (null) is reached.This is the pre-ES6 method for creating objects and setting prototypes.
// A constructor function to create a base object
function Animal(name) {
this.name = name;
}
// Add a method to the `Animal` prototype that will be shared by all instances
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
// Create a new object instance
const dog = new Animal("Rex");
// Call the method, which is found on the prototype
dog.speak(); // Output: Rex makes a noise.
This shows that dog itself does not have a speak method, but it is available via the prototype chain.
This is a more direct way to create a new object with a specified prototype.
const animalPrototype = {
speak() {
console.log(`${this.name} makes a noise.`);
}
};
const dog = Object.create(animalPrototype);
dog.name = "Rex";
dog.speak(); // Output: Rex makes a noise.
Inheritance is the process of creating a new object that acquires the properties and methods of an existing object. In JavaScript, this is achieved through the prototype chain.
When an object inherits from another, it becomes a link in the prototype chain. The end of every prototype chain is Object.prototype, which in turn has a prototype of null. This is why all objects in JavaScript implicitly inherit methods like toString().
ES6 classes provide a modern, cleaner syntax for achieving prototypal inheritance.
// Parent class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// Child class that inherits from Animal
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls the parent constructor
this.breed = breed;
}
// Override the `speak` method
speak() {
console.log(`${this.name} barks.`);
}
}
const mutt = new Dog("Buddy", "Mutt");
mutt.speak(); // Output: Buddy barks.
Object.create() for clean inheritance without constructors.Array.prototype) โ with caution.Object.prototype.class and extends for modern inheritance.this refers to the calling object, not the prototype. | Classes-ES6-Javascript | Encapsulation | |