Home > Web Front-end > JS Tutorial > body text

Why should we inherit javascript inheritance_Basic knowledge

WBOY
Release: 2016-05-16 17:48:20
Original
930 people have browsed it
Quiz1
Does Javascript really need classes?
Let’s first look at some features of other object-oriented languages ​​with classes (such as Java).

Superclass and subclass
Superclass and Subclass are not to solve the problem of father and son, but to solve the inclusion relationship of classes Yes, we use Sub to represent "subclass" and Sup to represent "parent class", then there is:
 Sub Sup
There is a difference. For example, usually we can use subclasses as parent classes, but When recognizing people, we cannot regard the son as the father.
In other words, parent classes and subclasses are not designed to solve the problem of the same methods or attributes between classes.

For example
Some people like to do this:
We need some classes of animals in order to create some moving animals on the screen, but some of the moving animals are in the air Flying and some walking on the road.
So create two parent classes, one is Fly and the other is Walk:
Copy the code The code is as follows:

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

Then Lion They (you can also build some other animals walking on the road) belong to the Walk category, and the eagles (you can also build some other animals flying in the sky) belong to the Fly category:
Copy code The code is as follows:

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

Finally create some instances of the Lion and Eagle classes, call the corresponding methods, 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 hits his head and wants to have an animal called Pegasus. They can fly in the sky, walk on the road, and sometimes fly. Time to walk.
In this case, this solution is completely useless.

Why did this design fail?
Inheritance is conditional, and the subclass must be able to strictly transform upward (become a parent class).
In the above example:
Lion is assumed to be equivalent to a walking animal (Walk), and Eagle is assumed to be equivalent to a flying animal (Fly).
This seems successful because the subclass can be strictly upward casted, but it has hidden dangers.
When a kind of Pegasus intervened, we discovered that lions are actually just "walking animals" and eagles are actually just "flying animals". This does not mean that animals can only fly or walk throughout their lives. , so the Pegasus, which can both fly and walk, cannot find its own home.
This example well proves that subclasses and parent classes are not designed to solve the problem of having the same methods between classes:
Some animals can walk and need to have the method Walk, but this should not be done by the child class. Class and parent class implementation.

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();
}
}

Composition is simply creating objects of the original class inside the new class. So combination is to solve the problem of having the same methods between classes. In this example:
Walk is regarded as "the set of methods that walking animals should have", and similarly Fly is regarded as "the set of methods that walking animals should have", so for Pegasus, we only need Just combine Walk and Fly.

The purpose of inheritance
Inheritance is not the only way to reuse code, but inheritance has its advantages:
Subclasses can be transformed upwards into parent classes.
In this way we can ignore all subclass differences and operate as the same class, for example:
We have methods fn(A), fn(B), these two methods are actually similar, we want 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, 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 true.
Because Javascript itself is a weakly typed language, it does not pay attention to the type of the object it operates before (because it does not need to be compiled). It will only succeed or an error will occur.
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 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 8 years and I have never found the need to use superclass functions. The idea of ​​superclasses is very important in classical design patterns, but it is not necessary in patterns based on prototypes and functions. I now feel that my early attempts to support classic mode in Javascript were a bad decision.

Safe 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 weakly typed scripting language, has to do this in order to simulate a strongly typed object-oriented language and set up a safe environment:
Copy code The code is as follows:

class ShopProductWriter{
public function write( $shopProduct ){
if( ! ( $shopProduct instanceof CdProduct ) && ! ( $shopProduct instanceof BookProduct ) ){
die( "Input wrong type" );
}
//If the type is correct, execute some code
}
}

— —PHP Objects, Patterns, and Practtice Third Edition . Matt Zandstra
But this is just a very ugly solution.

Classic inheritance syntax sugar implementation
However, classic inheritance is still the method favored by many people. Therefore, YUI, Prototype, Dojo, and MooTools all provide their own implementation solutions.
Among the more common solutions, the syntax is roughly like this:
Copy code 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 just reassembles the passed in object and turns it into a prototype object. The new constructor in prototype.
Please see Reference 1 for specific implementation.

The classic inheritance syntax sugar of ECMAScript 6
For class libraries to implement their own implementations, resulting in a large number of classic inheritance syntaxes, the ECMA organization seems not satisfied, and they are trying to add more intuitive ones to ECMAScript 6 Classic inheritance syntax sugar:
Copy code 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
Actually, classic inheritance is not necessary in Javascript.
However, because many people like the classic inheritance model, related syntactic sugar is provided in the new version of ECMAScript 6.
However, in China, the widespread use of this syntactic sugar on the front end should be a distant story...

Quiz2
What about Javascript-specific inheritance?

Prototypal inheritance
Prototypal inheritance does not solve the collection inclusion relationship in classic inheritance. In fact, prototypal inheritance solves the subordination relationship. The mathematical expression is:
 Sub. prototype ∈ Sup
Child constructor (subtype) prototype is an instance object built by a parent constructor (parent type). The prototype is actually something that needs to be shared among subtype instances:
Copy code 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 borrowing, parasitism and other technologies can produce many different inheritance effects, but these technologies are only to solve some public and non-public issues of attributes and methods in prototype inheritance. Due to space issues, we will not discuss it further. If you are interested, you can refer to the relevant content of "Javascript Advanced Programming".

Thinking Questions
1. If the question about Pegasus at the beginning of the article is written in Javascript, how should it be designed? For example, we have the following two types:
Copy code The code is as follows:

function Walk() {
this.walk = function(){
//walk
};
}
function Fly(){
this.fly = function(){
/ /fly
};
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!