Why does javascript inherit? _ basic knowledge

Source: Internet
Author: User
This article describes in detail the inheritance of javascript and other related knowledge. Quiz1
Does Javascript really need classes?
First, let's take a look at some of the features of other Class-oriented object-oriented languages (such as Java.

Parent class and subclass
The parent class and Subclass are not designed to solve the problem between the father and son, but to solve the class inclusion relationship. We use Sub to represent the "Subclass ", if Sup is used to represent the "parent class", there are:
Sub Sup
This is different. For example, we can use child classes as parent classes, but we cannot regard son as a father when recognizing a person.
You can also say that the parent class and subclass do not have the same method or attribute between classes.

For example
Some people like to do this:
We need some animal classes to create some moving animals on the screen, but some moving animals fly in the air and some walk on the road.
Therefore, create two parent classes: Fly and Walk:

The Code is as follows:


Class Fly {
Fly (){}
}
Class Walk {
Walk (){}
}


Then the lions (who can also create other animals walking on the road) belong to the walking class, And the eagles (who can also create other animals flying on the sky) belong to the Fly class:

The Code is as follows:


Class Lion extend Walk {
}
Class Eagle extend Fly {
}


Finally, create some instances for the Lion and Eagle classes and call the corresponding methods. Some lions and e are moving on the screen.
But this may not be a good design. For example, if the boss suddenly takes a brain shot tomorrow, he wants an animal named Pegasus, which will fly in the sky and go on the road, sometimes you need to fly and walk.
In this case, this solution is useless.

Why did the design fail?
Inheritance is conditional, and subclass must be able to perform a strict upward Transformation (to become a parent class ).
In the above example:
Lion is assumed to be equivalent to walking, and Eagle is assumed to be equivalent to flying ).
This seems very successful, because the subclass can strictly transform upwards, but it has potential risks.
When Pegasus got involved, we found that lions were actually just "Walking animals", and the Eagles were actually "flying animals ", this does not mean that animals can only fly or walk for the rest of their lives, so the sky and horses that will fly and walk will not find their own ownership.
This example proves that the subclass and parent classes do not have the same method between classes:
Some animals will Walk and need to have the Walk method, but this should not be implemented by subclass and parent classes.

Combination
We can solve this problem as follows:

The Code is as follows:


Class Lion {
Walker = new Walk ();
Walk (){
Return walker. walk ();
}
}
Class Eagle {
Flyer = new Fly ();
Fly (){
Return flyer. fly ();
}
}
Class Pegasus {
Walker = new Walk ();
Flyer = new Fly ();
Walk (){
Return walker. walk ();
}
Fly (){
Return flyer. fly ();
}
}


Combination is a simple way to create original class objects within the new class. Therefore, the combination is used to solve the problem of having the same methods between classes. In this example:
Walking is regarded as a set of methods that an animal can Walk should possess. Similarly, Fly is regarded as a set of methods that an animal can Walk should possess. Therefore, for Pegasus ), we only need to combine the Walk and Fly.

Purpose of Inheritance
Inheritance is not the only method for code reuse, but inheritance has its advantages:
Sub-classes can be transformed to parent classes.
In this way, we can ignore all subclass differences and operate on them as the same class. For example:
We have methods fn (A) and fn (B). These two methods are actually similar and we want to reuse them.
Then we can set up A parent class C, where A is A subclass of C, and B is A subclass of C, so fn (C) can be reused on A and B.

Back to Javascript
But back to Javascript, we found that the above example is not true.
Because Javascript itself is a weak type language, it does not focus on the object type operated by itself before the operation (because it does not need to be compiled. It only succeeds or has an error.
At this time, inheritance is unnecessary. Then the class is not necessary.
I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. the super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake.
-- Douglas Crockford
I have been writing Javascript code for eight years, but I have never found that super functions are needed. The idea of superclass is very important in classical design models, but it is not necessary in models based on prototypes and functions. I think it is wrong to try to make Javascript support for the Classic mode in the early days.

Security Environment
Of course, you can manually determine the type and control the type of parameters to provide a safer environment.
For example, PHP, which is also a weak scripting language, has to do this to simulate the security environment of a strong object-oriented language:

The Code is as follows:


Class ShopProductWriter {
Public function write ($ shopProduct ){
If (! ($ ShopProduct instanceof CdProduct )&&! ($ ShopProduct instanceof BookProduct )){
Die ("input error type ");
}
// Execute some code if the type is correct
}
}


-- PHP Objects, Patterns, and Practtice Third Edition. Matt Zandstra
But this is just an ugly solution.

Classical inheritance syntax sugar implementation
However, classic inheritance is still a popular method. Therefore, YUI, Prototype, Dojo, and MooTools all provide their own implementation solutions.
In the more common scheme, the syntax is like this:

The Code is as follows:


Var Person = Class. extend ({
Init: function (isDancing ){
This. dancing = isDancing;
}
});
Var Dancer = Person. extend ({
Init: function (){
This. _ super (true );
}
});
Var n = new Dancer ();
Alert (n. dancing); // true


The most important implementation is the implementation of this. _ super. In fact, the extend function only re-assembles the passed objects into a prototype object, which is in the prototype of the new constructor.
For more information, see document 1.

The classic inheritance syntax sugar of ECMAScript 6
The implementation of each class library leads to a large number of classical inheritance syntaxes, and The ECMA organization seems not satisfied. They try to add a more intuitive classical inheritance syntaxes in ECMAScript 6:

The Code is as follows:


Class Animal {
Constructor (name ){
This. name = name;
}
SayName (){
Console. log (this. name );
}
}
Class Dog extends Animal {
Constructor (name ){
Super (name );
}
Bark (){
Console. log ("Woof! ");
}
}


Summary
In fact, classic inheritance is not necessary in Javascript.
However, because many people prefer the classic inheritance model, the new version of ECMAScript 6 provides syntactic sugar.
However, in China, it is a distant story that the front-end wants to widely use the syntactic sugar ......

Quiz2
What about the unique inheritance of Javascript?

Prototype inheritance
Prototype inheritance does not solve the set inclusion relationship in the classic inheritance. In fact, prototype inheritance solves the subordination. It is expressed in mathematics as follows:
Sub. prototype ε Sup
A child Constructor (child type) prototype is an instance object built by a parent Constructor (parent type. The prototype is actually something that needs to be shared in a child-type instance:

The Code is as follows:


Function Being (){
This. living = true;
}
Being. prototype. walk = function (){
Alert ("I'm walking ");
};
Function Dancer (){
This. dancing = true;
}
Dancer. prototype = new Being ();
Dancer. prototype. dance = function (){
Alert ("I'm dancing ");
};
Var one = new Dancer ();
One. walk ();
One. dance ();


Using borrow, parasitic, and other technologies can produce many different inheritance effects, but these technologies are only used to solve some public and non-public problems of attributes and methods in prototype inheritance. Due to space issues, I will not discuss them. If you are interested, please refer to the related content of Javascript advanced programming.

Questions
1. At the beginning of the article, I Would Like To design a question about Pegasus on Javascript? For example, we have two types:

The Code is as follows:


Function Walk (){
This. walk = function (){
// Walk
};
}
Function Fly (){
This. fly = function (){
// Fly
};
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.