Explain how inheritance works in JavaScript.
sobes.tech AI
Answer from AI
Inheritance in JavaScript is based on prototypes. Each object has an internal property [[Prototype]] (accessible via __proto__ or Object.getPrototypeOf()), which points to another object.
When attempting to access a property or method of an object, if it is not found directly on the object, JavaScript searches for it in the object's [[Prototype]], then in the [[Prototype]] of the prototype, and so on up the prototype chain until it reaches the end (Object.prototype), whose [[Prototype]] is null.
This is prototype inheritance.
In ECMAScript 2015 (ES6), classes are syntactic sugar over prototype inheritance. They provide a more familiar syntax for working with prototypes and creating object hierarchies.
Example of using prototype inheritance before ES6:
// Parent constructor
function Animal(name) {
this.name = name;
}
// Parent method on prototype
Animal.prototype.sayHi = function() {
console.log(`Hi, I am ${this.name}`);
};
// Child constructor
function Dog(name, breed) {
// Call parent constructor
Animal.call(this, name);
this.breed = breed;
}
// Set child's prototype to the prototype of the parent
// and preserve the constructor reference
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// Add child's method
Dog.prototype.bark = function() {
console.log("Woof!");
};
// Create an instance of the child
const myDog = new Dog("Bobic", "Labrador");
// Use parent and child methods
myDog.sayHi(); // Outputs: Hi, I am Bobic
myDog.bark(); // Outputs: Woof!
Example of using classes (ES6):
// Parent class
class Animal {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hi, I am ${this.name}`);
}
}
// Child class extending Animal
class Dog extends Animal {
constructor(name, breed) {
// Call parent constructor
super(name);
this.breed = breed;
}
bark() {
console.log("Woof!");
}
}
// Create an instance of the child class
const myDog = new Dog("Rex", "German Shepherd");
// Use parent and child methods
myDog.sayHi(); // Outputs: Hi, I am Rex
myDog.bark(); // Outputs: Woof!
Key points of inheritance in JavaScript:
- Prototypes: Every object has a prototype.
- Prototype chain: When searching for a property or method, prototypes are traversed up the chain.
[[Prototype]]: Internal property pointing to the prototype.__proto__: Deprecated but commonly used way to access[[Prototype]].Object.getPrototypeOf(): Recommended way to access[[Prototype]].- Constructors and
prototype: Used before ES6 to create objects and set their prototypes. - Classes (ES6): Syntactic sugar for prototype inheritance, using keywords
class,extends,super.