Javascript inheritance
Created By: chatGPT
In JavaScript, inheritance is a way to facilitate code reuse and establish a relationship between different objects, allowing one object to inherit properties and methods from another. There are primarily two ways to implement inheritance: prototypal inheritance and classical inheritance. In ES5 and earlier, prototypal inheritance is the most common method.
function Parent() {
this.parentProperty = 'I am a parent';
}
Parent.prototype.parentMethod = function() {
console.log('This is a method from the parent.');
};
function Child() {
Parent.call(this); // Call the parent constructor
this.childProperty = 'I am a child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.childMethod = function() {
console.log('This is a method from the child.');
};
Creating Instances: You can create instances of the
Child
class, which allows them to access both parent and child properties and methods.const childInstance = new Child();
console.log(childInstance.parentProperty); // Output: I am a parent
console.log(childInstance.childProperty); // Output: I am a child
childInstance.parentMethod(); // Output: This is a method from the parent.
childInstance.childMethod(); // Output: This is a method from the child.
With the introduction of ES6, JavaScript also supports class syntax, which provides a clearer and more intuitive way to implement inheritance.
class Parent {
constructor() {
this.parentProperty = 'I am a parent';
}
parentMethod() {
console.log('This is a method from the parent.');
}
}
class Child extends Parent {
constructor() {
super(); // Call the parent constructor
this.childProperty = 'I am a child';
}
childMethod() {
console.log('This is a method from the child.');
}
}
Instance Creation: The instantiation process is similar to the previous example and allows access to inherited functionalities as well.
const childInstanceES6 = new Child();
console.log(childInstanceES6.parentProperty); // Output: I am a parent
console.log(childInstanceES6.childProperty); // Output: I am a child
childInstanceES6.parentMethod(); // Output: This is a method from the parent.
childInstanceES6.childMethod(); // Output: This is a method from the child.