Home >Web Front-end >JS Tutorial >Javascript playing with inheritance (3)_javascript skills
First, let’s look at non-mainstream inheritance one: instance inheritance.
I won’t talk so much nonsense. Since it is non-mainstream inheritance, it must not be commonly used. Since it still exists if it is not commonly used, there is only one factor. It is used in specific situations. The instance inheritance method is mainly used for the inheritance of core objects, and it is also the only way to solve the inheritance of core objects so far.
The inheritance of core objects has a certain value, such as the Error object. Our company may need to implement an Error class ourselves to simplify future development. At this time, I will use the instance inheritance method to inherit Error.
The code is as follows:
Okay, let’s test:
The results satisfy us:
Okay, without further ado, this is a non-mainstream inheritance method. It is basically only used for inheritance of core objects. Just remember it!
Let’s take a look at non-mainstream inheritance 2: copy inheritance method.
As the name suggests, copy inheritance is the inheritance of objects through copying. What is copied? Obviously, it is the properties and methods of the object. Remember that in Javascript, a class is actually a Hashtable? If you can't remember it, go back and review the basics. I may write an article about Javascript objects in a while.
It will be easy to handle once you understand this, just look at the code:
First write an Extend method:
Okay, let’s write some code to see how to use it:
A discerning person can see at a glance that the shortcomings of this method are too obvious:
When copying the object’s attribute methods one by one, what is actually used is reflection. I won’t go into details about the damage that reflection does to efficiency.
Similar to prototypal inheritance, the parent class object must be initialized. When the inheritance relationship is determined, but the parameters are not yet certain, it will not work!
In short, this method is generally not used.
Okay, let’s talk about something commonly used. Mixed inheritance!
This is based on two mainstream inheritance methods. Comparing the two inheritance methods, we can find that the advantages and disadvantages of the two inheritance methods are complementary, so it is easy to handle, let’s mix them together!
Test passed!
This is a relatively perfect solution, but it increases the complexity of the code, so the specific solution depends on everyone's choice in practice.
These are the ways to play with inheritance in Javascript. You are welcome to continue to pay attention to my other articles.