- Published on
Prototypal Inheritance in JavaScript
- Authors
- Name
- Nali Thephavong Haehn
In JavaScript, objects can inherit properties and methods from other objects, this means that every object has a prototype (a.k.a. a definition used to create the object). Prototypal inheritance is a way to create a new object from another object's definition.
Let's Talk Code
Consider this object constructor function:
const Pet = function (type, name, birthYear) {
this.type = type;
this.name = name;
this.birthYear = birthYear;
this.calcAge = function () {
return 2023 - this.birthYear;
};
};
When we instantiate a new Pet object using the above constructor function, we re-create all of the properties as well as the methods defined within that constructor function in another object:
const myFirstPet = new Pet("Dog", "Ranger", 2010);
console.log(myFirstPet.calcAge()); // returns 13
With every declaration of Pet
, our code's performance gets incrementally worse, so a better way to do this would be to store methods in the object's prototype instead of the constructor function:
const Pet = function (type, name, birthYear) {
this.type = type;
this.name = name;
this.birthYear = birthYear;
};
Pet.prototype.calcAge = function () {
return 2023 - this.birthYear;
};
const mySecondPet = new Pet("Dog", "Kiko", 2009);
console.log(mySecondPet.calcAge()); // returns 14
The result of the above code then is instead of re-creating the calcAge
method in mySecondPet
, it creates a reference to the calcAge
function in the prototype.
An even better approach is to use classes to define your objects, so you don't have to manipulate the prototype property directly:
class Pet {
constructor (type, name, birthYear) {
this.type = type;
this.name = name;
this.birthYear = birthYear;
}
calcAge () {
return 2023 - this.birthYear;
}
}
const myThirdPet = new Pet("Cat", "Moana", 2019);
console.log(myThirdPet.calcAge()); // returns 4