In this tutorial, we aim to explore and understand the concepts of prototypes and inheritance in JavaScript Object Oriented Programming (OOP).
By the end of this tutorial, you will learn:
Basic understanding of JavaScript is required. Familiarity with Object Oriented Programming would be useful but not necessary.
In JavaScript, every object has a prototype. The prototype is itself an object, and all objects inherit their properties and methods from their prototype.
let animal = {
eats: true
};
let rabbit = Object.create(animal);
console.log(rabbit.eats); // true
In the above example, rabbit
inherits the eats
property from the animal
object.
In JavaScript, objects can inherit from other objects. This is known as prototype inheritance.
let animal = {
eats: true,
walk() {
console.log("Animal walk");
}
};
let rabbit = Object.create(animal);
rabbit.walk(); // Animal walk
In this example, rabbit
inherits the walk
method from the animal
object.
function Rabbit(name) {
this.name = name;
}
Rabbit.prototype.eat = function() {
console.log(this.name + ' eats.');
}
let rabbit1 = new Rabbit('White Rabbit');
rabbit1.eat(); // White Rabbit eats
In this example, we add a method eat
to the prototype of Rabbit
. All instances of Rabbit
will have this method.
function Animal(name) {
this.name = name;
}
Animal.prototype.walk = function() {
console.log(this.name + ' walks.');
}
function Rabbit(name) {
this.name = name;
}
Rabbit.prototype = Object.create(Animal.prototype);
let rabbit1 = new Rabbit('Brown Rabbit');
rabbit1.walk(); // Brown Rabbit walks
In this example, Rabbit
inherits from Animal
by setting its prototype to an instance of Animal
.
In this tutorial, we have covered:
Next, you could explore more about JavaScript OOP, including classes and constructors. Here are some helpful resources:
Create an object cat
that inherits from animal
and add a method meow
to cat.
let animal = {
eats: true
};
let cat = // Your code here
cat.meow(); // should log "Cat meows"
Modify the Rabbit
function to accept name
and color
properties. Make sure color
is available to all instances and methods of Rabbit
.
function Rabbit(name) {
this.name = name;
}
// Your code here
let rabbit1 = new Rabbit('Grey Rabbit', 'grey');
console.log(rabbit1.color); // should log "grey"
let animal = {
eats: true
};
let cat = Object.create(animal);
cat.meow = function() {
console.log("Cat meows");
};
cat.meow(); // Cat meows
function Rabbit(name, color) {
this.name = name;
this.color = color;
}
let rabbit1 = new Rabbit('Grey Rabbit', 'grey');
console.log(rabbit1.color); // grey
In the above solution, we added a color
property to the Rabbit
constructor function. Now, color
is available to all instances and methods of Rabbit
.