Книга: Functional Programming in JavaScript
Назад: JavaScript's object-oriented implementation – using prototypes
Дальше: JavaScript's prototype chain

Inheritance

Before we go much further, let's make sure we fully understand the concept of inheritance in object-oriented programming. Class-based inheritance is demonstrated in the following pseudo-code:

class Polygon {   int numSides;   function init(n) {     numSides = n;   } } class Rectangle inherits Polygon {   int width;   int length;   function init(w, l) {     numSides = 4;     width = w;     length = l;   }   function getArea() {     return w * l;   } } class Square inherits Rectangle {   function init(s) {     numSides = 4;     width = s;     length = s;   } }

The class is the parent class the other classes inherit from. It defines just one member variable, the number of sides, which is set in the function. The subclass inherits from the class and adds two more member variables, and , and a method, . It doesn't need to define the variable because it was already defined by the class it inherits from, and it also overrides the function. The class carries on this chain of inheritance even further by inheriting from the class for its method. By simply overriding the function again such that the length and width are the same, the function can remain unchanged and less code needs to be written.

In a traditional OOP language, this is what inheritance is all about. If we wanted to add a color property to all the objects, all we would have to do is add it to the object without having to modify any of the objects that inherit from it.

Назад: JavaScript's object-oriented implementation – using prototypes
Дальше: JavaScript's prototype chain

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)