SoFunction
Updated on 2025-03-06

Summary of inherited operation examples of JavaScript class

This example summarizes the inheritance operations of JavaScript classes. Share it for your reference, as follows:

1. Classical inheritance

The first thing to do is create the constructor. By convention, its name is the class name, and the first letter should be capitalized. In the constructor, use keywords to create an instance propertythis. The class method is added toprototypein object. To create an instance of this class, just combine the keywordsnewJust call this constructor.

/* Class Person. */
function Person(name) {
  = name;
}
 = function() {
 return ;
}
var reader = new Person('John Smith');
();

2. Prototype chain

Each object in JavaScript has a nameprototype, this property either points to another object or is null. When accessing a member of the object, if this member is not seen in the current object, it will search in the object referred to by prototype. If it is still not found, each prototype object will be accessed one by one along the prototype chain until the member is found. This means that one class inherits another class, just subclassesprototypeSet it as an instance of the superclass.

In order for Author to inherit Person, Author'sprototypeSet as an instance of Person. The last step is toprototypeofconstructReset the attribute to Author(becauseprototypeWhen the property is set to an instance of Person, itsconstructThe attributes are erased.

function Author(name, books) {
 (this, name); // Call the superclass' constructor in the scope of this.
  = books; // Add an attribute to Author.
}
 = new Person(); // Set up the prototype chain.
 = Author; // Set the constructor attribute to Author.
 = function() { // Add a method to Author.
 return ;
};
var author = [];
author[0] = new Author('Dustin Diaz', ['JavaScript Design Patterns']);
author[1] = new Author('Ross Harmes', ['JavaScript Design Patterns']);
(author[1].getName());
(author[1].getBooks());

3. extend function

To simplify the declaration of a class, the entire process of derived subclasses can be wrapped in a function called extend. Its function with other languagesextendThe keyword is similar, that is, to create a new class based on the structure of a given class:

function extend(subClass, superClass) {
 var F = function() {};
  = ;
  = new F();
  = subClass;
}

In fact, what I did was the same as before. It's set firstprototype, then put it againconstructorReset to the appropriate value. And an empty function is used in the middle, so that the instance of the superclass can be avoided. useextendInheritance writing:

function Person(name) {
  = name;
}
 = function() {
 return ;
}
/* Class Author. */
function Author(name, books) {
 (this, name);
  = books;
}
extend(Author, Person);
 = function() {
 return ;
};

But one problem above is that the name of the superclass Person is solidified in the declaration of the Author class. A more universal approach should be like this:

/* Extend function, improved. */
function extend(subClass, superClass) {
 var F = function() {};
  = ;
  = new F();
  = subClass;
  = ;
 if( == ) {
   = superClass;
 }
}
/* Class Author. */
function Author(name, books) {
 (this, name);
  = books;
}
extend(Author, Person);
 = function() {
 return ;
};
 = function() {
 var name = (this);
 return name + ', Author of ' + ().join(', ');
};

thisextendAfter improvement, there is an additional superclass attribute, which can weaken the coupling between Author and Person.extendThe following three lines are used to ensure that the superclass constructor has been set correctly. With the superclass attribute, you can directly call methods in the superclass. This can come in handy when both redefining a method of the superclass and wanting to access its implementation in the superclass. For example, in order to redefine the method of the same name in the Person class with a new getName method, you can use it firstGet the author's name and then add new information again.

4. Prototype inheritance

Prototype inheritance is completely different from class inheritance. When we learn it, it is best to forget all our knowledge about classes and instances and think only from the perspective of objects. When using prototype inheritance, you do not need to use classes to define the structure of the object, just create an object directly. This object can then be used by a new object, which is called a prototype object.

The following is a prototype object to redesign the above Person and Author:

var Person = {
 name: 'default name',
 getName: function() {
  return ;
 }
};
var reader = clone(Person);
alert(()); // This will output 'default name'.
 = 'John Smith';
alert(()); // This will now output 'John Smith'.

cloneFunctions can be used to create a new Person class object, create an empty object, and the prototype object of the object is set to person. When a method cannot be found in the new object, it will be searched in the prototype object.

You don't have to define a Person subclass to create an Author, just perform a clone:

var Author = clone(Person);
 = []; // Default value.
 = function() {
 return ;
}

You can then redefine the methods and properties in that clone. Person's default value can be modified. New properties and methods can also be added. This creates a new prototype object that you can use to create a new Author object:

var author = [];
author[0] = clone(Author);
author[0].name = 'Dustin Diaz';
author[0].books = ['JavaScript Design Patterns'];
author[1] = clone(Author);
author[1].name = 'Ross Harmes';
author[1].books = ['JavaScript Design Patterns'];
author[1].getName();
author[1].getBooks();

How to write clone function:

function clone(object) {
  function F() {}
   = object;
  return new F;
}

5. Comparison between prototype inheritance and class inheritance

You can summarize it yourself,
Analyze from memory, scope of application, advantages and disadvantages, etc.

6. Organic class

There is a method to reuse code without strict inheritance. If you want to apply a function to multiple classes, you can use the extended method to let these classes share functions. The general approach is to create a method class that contains various general methods, and then expand other classes. This type of method class that contains general methods is called a metabolized class. They are usually not instantiated and called directly. The purpose of their existence is to provide their own methods to other classes.

var Mixin = function() {};
 = {
 serialize: function() {
  var output = [];
  for(key in this) {
   (key + ': ' + this[key]);
  }
  return (', ');
 }
};
augment(Author, Mixin);
var author = new Author('Ross Harmes', ['JavaScript Design Patterns']);
var serializedString = ();
function augment(receivingClass, givingClass) {
 for(methodName in ) {
  if(![methodName]) {
   [methodName] = [methodName];
  }
 }
}

But sometimes you don't need all methods, so we also need to provide additional parameters to choose the method we need. If not provided, copy them all.

function augment(receivingClass, givingClass) {
 if(arguments[2]) { // Only give certain methods.
  for(var i = 2, len = ; i < len; i++) {
   [arguments[i]] = [arguments[i]];
  }
 }
 else { // Give all methods.
  for(methodName in ) {
   if(![methodName]) {
    [methodName] = [methodName];
   }
  }
 }
}

For more information about JavaScript, you can also view the topic of this site: "JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.