Prototypal Inheritance
Object Literal Based
// Define a prototype object
const animal = {
eats: true,
walk() {
console.log("Animal walks");
}
};
// Create a new object that inherits from 'animal'
const dog = Object.create(animal);
dog.bark = function() {
console.log("Dog barks");
};
dog.walk(); // Inherited from 'animal': "Animal walks"
dog.bark(); // Specific to 'dog': "Dog barks"
console.log(dog.eats); // Inherited property: true
Constructor Functions and Prototypal Inheritance
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
const john = new Person("John");
john.greet(); // "Hello, my name is John"
ES6 Classes and Prototypes
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const myDog = new Dog("Rex");
myDog.speak(); // Rex barks