An example of javascript inheritance mechanism

  • 2020-03-30 04:21:27
  • OfStack

This article illustrates the javascript inheritance mechanism. Share with you for your reference. Specific analysis is as follows:

It is difficult to understand the inheritance mechanism of javascript when you are just learning javascript. It has no concept of "subclass" and "parent class", and no distinction between "class" and "instance". It relies on a very strange "prototype chain" pattern to realize inheritance.

I spent a lot of time, studied this part, and took a lot of notes. But all belong to forced memory, can not fundamentally understand.

How to create a class

Suppose there is a class called Person:

var Person = function(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.getName = function() {
    return this.name;
}

As above: Person represents all the people on the earth, and everyone has these two basic attributes: name and age; Now we're going to implement a student class, and then we know; The student is also a person, and the student also has attributes such as name and age; Now the question is how do you put this together?
Let's take a look at how a pure object-oriented language does it (e.g. Actionscript 3)
class Students extend Person {}; // Very simple, one line of code; It's more of a word --extend

Ii. How can we do it with js

Before explaining the implementation of js inheritance mechanism, let's first understand the prototype chain of js:

var person = new Person('Poised-flw', 21);
person.getName(); // "Poised-flw"

In terms of the getName() method above, how is it executed? The first thing I'm going to do is I'm going to look in the Person function for a method called getName (), and I'm going to find none; Then I went to person.prototype and found it! And then it calls, what if it doesn't? Continue to follow prototype in the same way until you find a way or reach the top of the prototype chain!

For example, there is now a constructor called DOG that represents the prototype of the DOG object.

  function DOG(name){
    this.name = name;
  }

Using new for this constructor generates an instance of the dog object.
  var dogA = new DOG(' Heavy hair ');
  alert(dogA.name); // Heavy hair

Notice the this keyword in the constructor, which represents the newly created instance object.

Disadvantages of the new operator

One drawback to using constructors to generate instance objects is the inability to share properties and methods.
For example, in the constructor of the DOG object, you set the common attribute species of an instance object.

  function DOG(name){
    this.name = name;
    this.species = ' canine ';
  }

Then, generate two instance objects:
  var dogA = new DOG(' Heavy hair ');
  var dogB = new DOG(' at ');

The species attribute of the two objects is independent, and modifying one of them does not affect the other.
  dogA.species = ' The cat ';
  alert(dogB.species); // According to " canine " And is not affected by dogA The influence of

Each instance object has its own copy of its properties and methods. This is not only impossible to share data, but also a huge waste of resources.

So: the idea of inheritance: through js unique prototype chain to achieve the inheritance mechanism!

Inheritance based on prototype chain

1. Directly inherit the implementation

var Students = function(name, age, sid) {
    Person.call(this, name, age);
    this.sid = sid;
}
Students.prototype = new Person(); //Put the Person on the Students prototype chain to implement the inheritance mechanism
Students.prototype.constructor = Students;
Students.prototype.getResults = function() {
    //Get the student's grade
}

Must not be less Students. The prototype. The constructor = Students this line! When a constructor is defined, its default prototype is an Object instance, and its constructor property is automatically set to the function itself!! If you manually set prototype to another object, the new object will not have the contructor value of the original object, so you need to reset its constructor property. Such as:
var Test = function() {
    this.time = "now";
}
console.log(Test.prototype); //Object {} an empty Object
console.log(Test.prototype.constructor); //The function () {this. Time = "now"; }, and the function itself
//Manually change the prototype property of Test
Test.prototype = {
    someFunc: function() {
        console.log('hello world!');
    }
};
console.log(Test.prototype.constructor); // function Object() { [native code] }
// Then you will find out that the finger is completely wrong and change it manually prototype Property when you need to change it constructor Point to the ;

The above test will show you why you need to modify the constructor value.

2. Encapsulates the inherited function extend

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

In fact, the function of this function is just a encapsulation of the above inheritance process, the difference is:
Inherited only the prototype property of superClass, not the properties in the superClass constructor;
This has the advantage of reducing the overhead of going to a new constructor!
The problem with this, of course, is that you can't simply have subClass inherit all the properties of superClass through this function
Improvement:
//Continue to add a line of code in the Students constructor: 
Person.call(this, name, age);

Five, the summary

Using the prototype chain principle of js, we can easily implement the inheritance mechanism of js, although not very strict, but my goal has been achieved: duplicate code as much as possible!


Related articles: