In fact, when I first started learning JS, I looked at the implementation of inheritance. At that time, I just tried to understand the code segments I saw from the book. I rethinked it today and felt that this was the result of the evolution of thinking exploration.
Inheritance means reuse.
If you put aside the inherent idea of inheritance and let b reuse the members of a, the simplest and most rude way to do it, b=a;
Then, the question is: Any change to b is a change to a (the same object).
OK, then copy one. If the shallow copy is not safe enough, use deep copy.
Problem: The code is reused, but the memory is wasted (regardless of variables or methods, it is an object in JS).
If you don't copy, read and write, you can use JS prototype, b.__proto__ = a. Generally, we do not change __proto__ directly, it is too violent. JS provides a method that can achieve the goal more "gentle" - Object.create(b).
This method is feasible, but this is just a reuse mode for specific objects. What if we achieve "the object created using ConstructorB can reuse the prototype of the object of ConstructorA"?
The answer is: treat b as ConstructorB.prototype, and treat a as ConstructorA.prototype.
question:
Solution:
When declaring ConstructorB, the system will automatically ask ConstructorB.prototype.constructor=ConstructorB; in the above code, the constructor is thrown away and the constructor is added.
The above is the most basic inheritance. It is not within the scope of this article, about how subclasses call the constructor and members of the parent class more generally (such as this._super), how to implement the inheritance mode more generally (such as A=inheritFrom(B)), etc.
The above is the full content of the old-fashioned inheritance of JavaScript classes that the editor brings to you. I hope everyone will support Wulin.com more~