Why should JavaScript inherit the basics

Source: Internet
Author: User
Tags extend
Quiz1
does JavaScript really need classes (class)?
Let's first look at some of the features of other object-oriented languages (class), such as Java.

Parent class and child class
The parent class (superclass) and subclasses (subclass) are not meant to solve the problem of father and son, but to solve the inclusion relationship of the class, we use sub to represent "subclass" and "parent class" with SUP, then there are:
Sub Sup
There is a difference, for example, that we can usually use subclasses as parents, but we don't think of our sons as fathers.
Or it can be said that the parent class and subclass are not meant to resolve the same method or attribute between classes.

As an example
Some people like to do this:
We need some animal classes to create some moving animals on the screen, but some of the moving animals are flying in the air and some are walking on the road.
So create two parent classes, one is fly, one is walk:
Copy Code code as follows:

Class fly{
Fly () {}
}
Class walk{
Walk () {}
}

Then the Lions (and other animals on the road) belong to the Walk category, and eagles (and other animals that fly in the sky) belong to the fly Category:
Copy Code code as follows:

Class Lion Extend walk{
}
Class Eagle Extend fly{
}

Finally, create some instances of the lion and Eagle classes and invoke the appropriate method, and there will be some lions and eagles moving on the screen.
But this may not be a good design, for example, tomorrow the boss suddenly a pat on the brain, he wants to have a kind of animal called Tianma (Pegasus), they will fly in the sky, and will walk on the road, sometimes to fly, time to walk.
In this case, the scheme is completely useless.

Why did the design fail?
Inheritance is conditional, and subclasses must be able to transition strictly upward (into a parent class).
In the example above:
Lions (Lion) are assumed to be equated with walking animals (Walk), and Eagles (Eagle) are assumed to be equated with flying animals (Fly).
This seems to be a success, because the subclass can be strictly upward transition, but he has hidden trouble.
When a kind of Tianma (Pegasus) is involved in the inside, we found that the lion is actually just "walking animals", the eagle is actually only "flying animals", this does not mean that animals can only fly or walk, so that will fly and walk the Tianma can not find their own ownership.
This example is a good proof that subclasses and parent classes are not designed to solve the same method between classes:
Some animals walk and need to have a walking (Walk) method, but this should not be implemented by subclasses and parent classes.

Combination
We can solve this problem like this:
Copy Code code 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 ();
}
}

A combination is simply creating an existing class object inside a new class. So the combination is to solve the same method between classes. In this example:
Walk is treated as a "set of methods that a walking animal should have", and fly is treated as a collection of methods that "walking animals should have", so for Tianma (Pegasus), we just need to combine walk and fly.

Purpose of inheritance
Inheritance is not the only way to code reuse, but inheritance has his advantages:
Subclasses can be transformed up into parent classes.
This allows us to ignore all subclass differences and act as the same class, for example:
We have the method fn (A), FN (B), the two methods are actually similar, and we want to reuse them.
Then we can use a parent class C, where a is a subclass of C, and B is a subclass of C, then FN (c) can be reused on a and b.

back to JavaScript
But back to JavaScript, we found that the above example is not tenable.
Because JavaScript itself is a weakly typed language, it does not concern itself with the type of object it operates (because he does not compile). He can only execute success, or an error occurs.
At this time, inheritance seems unnecessary. Then the class is also not necessary.
I have been writing JavaScript for 8 years now, and I have never the once found to the use a need function. The super idea are fairly important in the classical pattern, but it appears to being unnecessary in the Prototypal and Functi Onal patterns. I now am early attempts to support the classical model in JavaScript as a mistake.
--douglas Crockford
I've been writing JavaScript code for 8 years, but I've never found it necessary to use superclass functions. The idea of super class is very important in classical design mode, but it is not necessary in the model of the prototype and function. I now feel that early attempts to get JavaScript to support Classic mode is a bad decision.

Security Environment
Of course, you can manually determine the type, control the type of parameters, and thus provide a more secure environment.
For example, PHP, also a weak-type scripting language, has to do so in order to simulate a strongly typed object-oriented language:
Copy Code code 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 it's just a very ugly plan.

Classical inheritance grammar sugar implementation
But classic inheritance is still the way many people like it. So Yui, Prototype, Dojo, MooTools have provided their own implementation plan.
Among the more common scenarios, the syntax is probably this:
Copy Code code 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 the This._super, in fact, the extend function just will be the incoming object reassembled, into a prototype object, the new constructor prototype.
See reference 1 for specific implementations.

ECMAScript 6 's classic inherited grammar candy
For the class library to implement their own, resulting in a large number of classic inheritance syntax, ECMA organizations appear to be dissatisfied, they are trying to add a more intuitive classical inheritance of syntactic sugars in ECMAScript 6:
Copy Code code 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, classical inheritance in JavaScript is not necessary.
However, many people like the classic inheritance model, so in the new version of ECMAScript 6 provides the relevant syntax sugar.
But in China, the front end wants to use this grammatical candy widely should be a distant story ...

QUIZ2
What about the JavaScript-specific inheritance?

prototype Inheritance
Prototype inheritance is not a solution to the collection inclusion relationship in classical inheritance, in fact, the prototype inheritance is to resolve the subordinate relationship, in the mathematical expression is:
Sub.prototype∈sup
A child constructor (subtype) prototype is an instance object built by a parent constructor (parent type). A prototype is actually something that needs to be shared in a subtype instance:
Copy Code code 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 ();

The use of borrowed, parasitic and other technologies can produce many different inheritance effects, but these techniques are only to solve the prototype inheritance in the properties and methods of some public and non-public problems. Due to the length of the issue will not be discussed, interested in the "JavaScript Advanced Programming" related content.

Study Questions
1. The beginning of the article on the question of Tianma (Pegasus), if in JavaScript, how should design it? For example, we have the following two types:
Copy Code code as follows:

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

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.