snippetjavascriptTip
How does JavaScript's prototypal inheritance differ from classical inheritance?
Viewed 0 times
classicaljavascriptinheritanceprototypalfromhowdoesdiffer
Problem
Both classical and prototypal inheritance are object-oriented programming paradigms. Objects in object-oriented programming are abstractions that encapsulate the properties of an entity. This is known as abstraction.
When dealing with multiple levels of abstraction, each level is more general or more specific. The more general abstraction of a more specific abstraction is called a generalization.
As mentioned previously, objects are abstraction of entities. We use either classes (classical inheritance) or prototypes (prototypal inheritance) to create generalizations of these objects. Generalizations are created by inheritance.
Consider an example:
When dealing with multiple levels of abstraction, each level is more general or more specific. The more general abstraction of a more specific abstraction is called a generalization.
As mentioned previously, objects are abstraction of entities. We use either classes (classical inheritance) or prototypes (prototypal inheritance) to create generalizations of these objects. Generalizations are created by inheritance.
Consider an example:
- We have two objects representing two pets: Max the dog and Claire the cat. Let's call them
maxandclairerespectively.
Solution
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
const max = new Dog();
max.name = 'Max';
const claire = new Cat();
claire.name = 'Claire';As mentioned previously, objects are abstraction of entities. We use either classes (classical inheritance) or prototypes (prototypal inheritance) to create generalizations of these objects. Generalizations are created by inheritance.
Consider an example:
- We have two objects representing two pets: Max the dog and Claire the cat. Let's call them
maxandclairerespectively. - All dogs have common characteristics. Therefore we can create an abstraction,
Dog, which encapsulates their common characteristics. We can use inheritance to pass characteristics fromDogtomax. - The same applies for cats, allowing us to create an abstraction,
Cat. Similarly,clairewill inherit characteristics fromCat. - Cats and dogs share some common characteristics. We can create a generalization,
Animal, to encapsulate those characteristics.DogandCatinherit these common characteristics fromAnimal.
Code Snippets
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
const max = new Dog();
max.name = 'Max';
const claire = new Cat();
claire.name = 'Claire';const animal = {};
const dog = Object.create(animal);
const cat = Object.create(animal);
const max = Object.create(dog);
max.name = 'Max';
const claire = Object.create(cat);
claire.name = 'Claire';Context
From 30-seconds-of-code: classical-vs-prototypal-inheritance
Revisions (0)
No revisions yet.