Inheritance

JavaScript's inheritance works differently from inheritance in other languages, which can be very confusing. ES6 classes provide a syntactic sugar attempting to alleviate the issues with using prototypical inheritance present in ES5.

To illustrate this, let's image we have a zoo application where types of birds are created. In classical inheritance, we define a base class and then subclass it to create a derived class.

Subclassing

The example code below shows how to derive Penguin from Bird using the extends keyword. Also pay attention to the super keyword used in the subclass constructor of Penguin, it is used to pass the argument to the base class Bird's constructor.

The Bird class defines the method walk which is inherited by the Penguin class and is available for use by instance of Penguin objects. Likewise the Penguin class defines the method swim which is not avilable to Bird objects. Inheritance works top-down from base class to its subclass.

Object Initialization

The class constructor is called when an object is created using the new operator, it will be called before the object is fully created. A consturctor is used to pass in arguments to initialize the newly created object.

The order of object creation starts from its base class and then moves down to any subclass(es).

  1. // Base Class : ES6
  2. class Bird {
  3. constructor(weight, height) {
  4. this.weight = weight;
  5. this.height = height;
  6. }
  7. walk() {
  8. console.log('walk!');
  9. }
  10. }
  11. // Subclass
  12. class Penguin extends Bird {
  13. constructor(weight, height) {
  14. super(weight, height);
  15. }
  16. swim() {
  17. console.log('swim!');
  18. }
  19. }
  20. // Penguin object
  21. let penguin = new Penguin(...);
  22. penguin.walk(); //walk!
  23. penguin.swim(); //swim!

Below we show how prototypal inheritance was done before class was introduced to JavaScript.

  1. // JavaScript classical inheritance.
  2. // Bird constructor
  3. function Bird(weight, height) {
  4. this.weight = weight;
  5. this.height = height;
  6. }
  7. // Add method to Bird prototype.
  8. Bird.prototype.walk = function() {
  9. console.log("walk!");
  10. };
  11. // Penguin constructor.
  12. function Penguin(weight, height) {
  13. Bird.call(this, weight, height);
  14. }
  15. // Prototypal inheritance (Penguin is-a Bird).
  16. Penguin.prototype = Object.create( Bird.prototype );
  17. Penguin.prototype.constructor = Penguin;
  18. // Add method to Penguin prototype.
  19. Penguin.prototype.swim = function() {
  20. console.log("swim!");
  21. };
  22. // Create a Penguin object.
  23. let penguin = new Penguin(50,10);
  24. // Calls method on Bird, since it's not defined by Penguin.
  25. penguin.walk(); // walk!
  26. // Calls method on Penguin.
  27. penguin.swim(); // swim!

原文: https://angular-2-training-book.rangle.io/handout/features/inheritance.html