SoFunction
Updated on 2025-04-04

A comprehensive example explanation of the inheritance of JavaScript classes

1. Inheritance in ES5

First, let's say we have a parent classPerson, and a method is defined inside the class and on the prototype chain:

function Person(name, age) {
   = name;
   = age;
   = function() {
    ('Hello, I am ', );
  }
}
 = function() {
  return  + ',' + ;
}

1.1 Modify the prototype chain

This is the most common inheritance practice by subclassingprototypePoint to an instance of the parent class to implement:

function Student() {
}
 = new Person();
 = 'Chao An';
 = 18;
const stud = new Student();
();

In this inheritance method,studAn object is both an instance of a subclass and an instance of a parent class. However, there are also disadvantages. In the constructor of the subclass, it is impossible to modify the attribute value inherited by the parent class by passing parameters, and can only be modifiedprototypemodify the method.

1.2 Calling the constructor of the parent class

function Student(name, age, sex) {
  (this);
   = name;
   = age;
   = sex;
}
const stud = new Student('Chao An', 18, 'male');
(); // Hello, I am Xia'an(); // Error

This method avoids the disadvantage of prototype chain inheritance, and directly calls the constructor of the parent class in the subclass. In this case,studAn object is just an instance of a subclass, not an instance of a parent class, and can only call methods defined in the parent class instance, and cannot call methods defined on the parent class prototype.

1.3 Combination inheritance

This inheritance method is a combination of the previous two inheritance methods.

function Student(name, age, sex) {
  (this);
   = name;
   = age;
   = sex;
}
 = new Person();
const stud = new Student('Chao An', 18, 'male');
();
();

This method combines the advantages of the above two inheritance methods and is also a standard inheritance method in the Node source code. The only problem is that the constructor of the parent class is called twice, respectively, setting the subclassprototypeand is called when instantiating a new object in the subclass, which causes some memory waste.

1.4 Prototype inheritance

Using an empty object as an intermediary, an object is assigned directly to the prototype of the empty object constructor.

function createObject(o) {
  // Create temporary classes  function f() {
  }
  // Modify the prototype of the class to o, so all instances of f will inherit the method on o   = o
  return new f()
}

Isn't this justIs it?createObjectPerform a shallow copy of the object passed into it, and the constructor is constructedfThe prototype points directly to the incoming object. The disadvantage of modifying the prototype chain is also not solved.

1.5 Parasitic inheritance

Based on prototype inheritance, enhance the object, return the constructor, or use prototype inheritance to perform shallow copying of a target object, enhancing the ability of this shallow copy.

function Student() {
  const clone = (Person);
   = 'Chao An';
  return clone;
}

It can also be combined with the previous method, so I will not repeat it here.

2. Inheritance in ES6

It can be used directly in ES6extendsKeywords to achieve inheritance are more concise in form. We also mentioned earlier that ES6 is correctClassThe improvement is to avoid developers from getting too entangled in syntax details.

We design astudentClasses inherit the previously definedpersonkind.

class Student extends Person {
  constructor(name, age, sex) {
    super(name, age);
     = sex;
  }
  getInfo() {
    return () + ',' + ;
  }
  print() {
    const info = ();
    (info);
  }
}
const student = new Student('Chao An', 18, 'male');
(); // Xia'an,18,male

In the code we defineStudentclass, called in its constructorsuperMethod, which calls the constructor of the parent class and binds the properties in the parent class to the child class.

superMethods can take parameters to indicate which parent class attributes will be inherited. In the code, subclasses usesuperInheritedPersonClassicnameas well asageAt the same time, another attribute is declaredsexproperty.

In a subclass,superThe method must be called because the subclass itself does not have its ownthisObject, must passsuperMethod to get the parent classthisObjects can besuperTry to print the subclass before function callthis, the code will have an undefined error.

If the subclass is not definedconstructorMethods, then they are automatically called within the default constructor.superMethod and inherit all properties of the parent class.

At the same time, in the subclass constructor, it must be called firstsuperMethods can be calledthisThe keyword declares other properties (if it exists), and this is also becausesuperBefore the call, the subclass has not yetthisThis is why.

class Student extends Person {
  constructor(name, age, sex) {
    (this); // Error
    super(name, age);
     = sex;
  }
}

In addition to being used in subclass constructors,superIt can also be used in class methods to refer to the methods of the parent class.

class Student extends Person {
  constructor(name, age, sex) {
    super(name, age);
     = sex;
  }
  print() {
    const info = (); // Call parent class method    (info);
  }
}

It is worth noting thatsuperYou can only call the parent class method, but not the parent class attributes, because the method is defined on the prototype chain, and the attributes are defined inside the class (just like combination inheritance, the attributes are defined inside the class).

class Student extends Person {
  constructor(name, age, sex) {
    super(name, age);
     = sex;
  }
  getInfo() {
    return ; // undefinded
  }
}

In addition, when the function of the subclass is called, all the subclasses are usedthis(Modify the parent classthisGet it), even if usedsuperTo call the parent class method, the subclass is still usedthis

class Person {
  constructor() {
     = 'Chao An';
     = 'male';
  }
  getInfo() {
    return  + ',' + ;
  }
}
class Student extends Person {
  constructor() {
    super();
     = 'An Xia';
     = 'Female';
  }
  print() {
    return ();
  }
}
const student = new Student();
(()); // Anxia, ​​Female(()); // Anxia,Female

In the above example,superThe parent class method is called, but the output content is the attribute of the subclass.superBound subclassthis

This is the end of this article about the comprehensive example of inheritance of JavaScript classes. For more related JS classes, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!