I often talk about inheritance of JavaScript classes.
In fact, I saw the implementation of inheritance when I first learned JavaScript. At that time, I just tried to understand the code snippet from the book. Today, I think again. It seems that this is the result of the evolution of thinking exploration.
Inheritance, that is, reuse.
If we leave aside the inherent idea of inheritance and allow B to reuse members of a, the simplest and most crude practice is B =;
So the question is: any change to B is a change to a (the same object ).
Okay, copy one copy. If the shortest copy is not secure enough, use the deep copy.
Problem: code is reused, but memory is wasted (both variables and methods are objects in JS ).
Do not copy, read-only, do not write, you can use the JS prototype, B. _ proto _ =. In general, we do not directly change _ proto __, which is too violent. JS provides a method that can be "gentle" to achieve the goal-Object. create (B ).
This method is feasible, but this is only the reuse mode of the specific object. What if we can "reuse the prototype of the ConstructorA object by using the object created by ConstructorB?
The answer is: Think of B as ConstructorB. prototype, and think of a as ConstructorA. prototype.
Problem:
Solution:
When declaring ConstructorB, the system will automatically let ConstructorB. prototype. constructor = ConstructorB; in the above Code, in order to reuse ConstructorA. prototype, the constructor is lost. Just add it.
The above is the most basic inheritance. How can a subclass more commonly call the constructor and members of the parent class (such as this. _ super), how to more commonly implement the inheritance mode (such as A = inheritFrom (B), and so on, not in the scope of this article ^ O ^
The above is all the content of the inheritance of JavaScript classes that xiaobian brings to you. I hope you can support more help ~