In fact, when I first started learning JS, I saw the implementation of inheritance. At that time, I was just trying to understand the code snippets from the book. I thought about it again today, and I feel that this is the result of the evolution of thinking.
Inheritance, that is, reuse.
If you put aside the inherent idea of inheritance and let b reuse the members of a, the simplest and crudest way is, b=a;
Then, here comes the problem: any changes to b, It is a change to a (the same object).
Okay, then make a copy. If the shallow copy is not safe enough, use a deep copy.
Problem: The code is reused, but the memory is wasted (whether it is a variable or a method, it is an object in JS).
Without copying, only reading and not writing, you can use the JS prototype, b.proto = a. Generally, we do not change the proto directly, as it is too violent. JS provides a method that can achieve the goal in a relatively "gentle" way - Object.create(b).
This method is feasible, but it is only the reuse mode of specific objects. What if "the object created by ConstructorB can reuse the prototype of the object of ConstructorA"?
The answer is: treat b as ConstructorB.prototype and a as ConstructorA.prototype.
Question:
Solution:
When declaring ConstructorB, the system will automatically let ConstructorB.prototype.constructor=ConstructorB; In order to reuse ConstructorA.prototype in the above code , if the constructor is lost, just add it.
The above is the most basic inheritance. Regarding how subclasses can call the constructor and members (such as this._super) of the parent class more generally, How to implement the inheritance pattern more generally (such as A=inheritFrom(B)), etc., is beyond the scope of this article^O^
The above is the detailed content of About inheritance of JavaScript classes (recommended). For more information, please follow other related articles on the PHP Chinese website!