SoFunction
Updated on 2025-02-28

Detailed explanation of JavaScript inheritance (I)

Object-oriented vs. Object-based

Almost every developer has development experience in object-oriented languages ​​(such as C++, C#, Java). In traditional object-oriented languages, there are two very important concepts - classes and instances. Classes define public behaviors and methods of a class of things; instances are a concrete implementation of a class. We also know that there are three important concepts in object-oriented programming - encapsulation, inheritance, and polymorphism.

But in the world of JavaScript, all these features seem to exist. Because JavaScript itself is not an object-oriented language, but an object-based language. There are some interesting features here, such as all things in JavaScript are objects, including strings, arrays, dates, numbers, and even functions. For example, the following example:

    // Define a function - add
function add(a, b) {
++;
return a + b;
}
// Because the function itself is an object,Here is the functionaddDefine an attribute,Used to record the number of times this function is called
= 0;

add(1 + 1);
add(2 + 3);
(); // 2

 

Simulate classes and inheritance in JavaScript

In an object-oriented language, we use classes to create a custom object. However, everything in JavaScript is an object.So what method can be used to create custom objects?

This requires the introduction of another concept - prototype. We can simply regard prototype as a template. The newly created custom objects are a copy of this template (actually not a copy but a link, but this kind of link is invisible, giving people the feeling that it is a copy).

Let's take a look at an example of creating a custom object through prototype:

    // Constructor
function Person(name, sex) {
= name;
= sex;
}
// definitionPersonPrototype,原型中的属性可以被自definition对象引用
= {
getName: function() {
return ;
},
getSex: function() {
return ;
}
}

Here we call the function Person the constructor, that is, the function that creates a custom object. It can be seen that JavaScript implements the functions of the class through constructors and prototypes.
Code to create a custom object (institialized class):

    var zhang = new Person("ZhangSan", "man");
(()); // "ZhangSan"

var chun = new Person("ChunHua", "woman");
(()); // "ChunHua"

When the code var zhang = new Person("ZhangSan", "man") is executed, the following things are actually done internally:

  • Create a blank object (new Object()).
  • The attributes (key-value pairs) in the copy are entered into this empty object (we mentioned earlier that when implemented internally, it is not a copy but a hidden link).
  • Pass this object into the constructor through this keyword and execute the constructor.
  • Assign this object to the variable zhang.

 

To prove that the prototype template is not copied into an instantiated object, but a link method, please see the following code:

    function Person(name, sex) {
= name;
= sex;
}
= 20;

var zhang = new Person("ZhangSan", "man");
(); // 20
// coverprototypeIn-houseageproperty
= 19;
(); // 19
delete ;
// Delete instance propertiesageback,This property value is fromprototypeGet it in
(); // 20

This hidden prototype link implemented within JavaScript is the warm soil on which JavaScript relies on and is also the basis for simulation implementation of inheritance.

 

How to implement simple inheritance in JavaScript?
The following example will create an employee class Employee which inherits all properties in the prototype prototype from Person.

    function Employee(name, sex, employeeID) {
= name;
= sex;
= employeeID;
}
// WillEmployeePrototype pointingPersonAn example of
// becausePersonAn instance ofPersonMethods in prototypes, soEmployeeAn instance ofPersonAll properties in the prototype。
= new Person();
= function() {
return ;
};

var zhang = new Employee("ZhangSan", "man", "1234");
(()); // "ZhangSan

 

The above implementation of inheritance is rough and there are many problems:

  • Person is instantiated when creating Employee constructor and prototype (hereinafter referred to as class), which is inappropriate.
  • Employee's constructor cannot call the constructor of the parent class Person, resulting in repeated assignments of name and sex attributes in the Employee constructor.
  • Functions in Employee will override functions of the same name in Person, without overloading mechanisms (and the previous one is the same type issue).
  • The syntax for creating JavaScript classes is too scattered and not as elegant as the syntax in C#/Java.
  • There is an error in the pointing of the constructor attribute in the implementation, which will be discussed in the second article.

We will perfect this example in Chapter 3.

 

Implementation of JavaScript inheritance

Because JavaScript itself does not have a complete class and inherited implementation, and we also see many problems in the way of implementing it manually, there are already many implementations for this challenging task online:

  • Douglas Crockford - Prototypal Inheritance in JavaScript
  • Douglas Crockford - Classical Inheritance in JavaScript
  • John Resig - Simple JavaScript Inheritance
  • Dean Edwards - A Base Class for JavaScript Inheritance
  • Prototype
  • Mootools
  • Extjs

This series of articles will analyze these implementations in depth one by one, and ultimately achieve an in-depth understanding of how to implement classes and inheritance in JavaScript.

In the next chapter, we will introduce relevant knowledge in class implementation, such as this, constructor, prototype, etc.