Implementation of js class inheritance _ basic knowledge

Source: Internet
Author: User
This article mainly introduces the implementation of js class inheritance. If you need it, you can refer to the purpose and benefits of using inheritance before you start to play with the code. In general, when designing classes, we want to reduce repetitive code and minimize coupling between classes. However, it is difficult to take both of them into consideration. We need to decide what method we should adopt based on the specific conditions and environment. Based on our understanding of inheritance in object-oriented languages, inheritance will bring direct strong coupling of classes. However, due to its unique flexibility, js can design strong coupling and weak coupling, efficient and inefficient code. The specific usage depends on the situation.

The following three methods are provided for js implementation inheritance: class inheritance, prototype inheritance, and metadata class. Here we will briefly describe the class-type inheritance, and briefly describe the latter two in the future. Please pay more attention and guide. Thank you.

Class inheritance.

The implementation of js class inheritance relies on the prototype chain. What is prototype chain? In js, an object has a property prototy, which returns an object type reference and is used to provide a set of basic functions of the object class.

We seem to have an impression on prototype. By the way, we often use code like this.

The Code is as follows:


Var Person = function (){
This. name = "liyatang ";
};
Person. prototype = {
// The basic functions of Person can be provided here
GetName: function (){
Return this. name;
}
}

We put the basic functions of the class in the prototype attribute, indicating that the object "Person" has the XXX function.

After understanding the prototype, you need to understand what a prototype chain is. When accessing a member (attribute or method) of an object, if the member is not found in the current object, js will search for it in the object indicated by the prototype property. If the Member is not found, search for the object indicated by prototype at the next level until it is found. Undifined is returned if it is not found.

What prompt does prototype chain give us? It is easy to think of, prototype chain means to let a class inherit from another class, just set prototype of the subclass to point to an instance of the parent class. This binds the members of the parent class to the subclass, because when a member cannot be found in the subclass, It is searched for in the parent class. (These two terms are not rigorous and are described in plain words only)

Next we need a Chinese class that inherits the name and getName members of the Person class.

The Code is as follows:


Var Chinese = function (name, nation ){
// Inheritance. You need to call the constructor of the parent class. You can use call to call the constructor. this points to Chinese.
// Enable the Person to call the Person Member in this scope.
Person. call (this, name );
This. nation = nation;
};
Chinese. prototype = Person. prototype;
// This cannot be the same as before, because the prototype attribute is overwritten.
// Chinese. prototype = {
// GetNation: function (){
// Return this. nation;
//}
//};
// Future methods must be added in this way
Chinese. prototype. getNation = function (){
Return this. nation;
};

The inheritance relationship is established. We call it in this way.

The Code is as follows:


Var c = new Chinese ("liyatang", "China ");
Alert (c. getName (); // liyatang

The class inheritance is completed in this way. If firebug is used to set a breakpoint at alert, the original Person. prototype is modified and the getNation method is added.

This is because the above Code Chinese. prototype = Person. prototype; this is the reference type, and the Person is modified when the Chinese is modified. This is intolerable in itself, and the strong coupling between classes is formed. This is not our result.

We can create another object or instantiate an instance to weaken coupling.

The Code is as follows:


// First
// Chinese. prototype = new Person ();
// Type 2
// Var F = function (){};
// F. prototype = Person. prototype;
// Chinese. prototype = F. prototype;

What is the difference between the two methods. Add an empty function F in the second type to avoid creating an instance of the parent class, because the parent class may be large, the constructor of the parent class has some side effects, or executes a large number of computing tasks. Therefore, we recommend the second method.

So far, it's over, not yet! There is a constructor under the prototype attribute of the object, which saves reference to the function used to construct a specific object instance. According to this statement, Chiese. prototype. constructor should be equal to Chinese, not actually.

Recall that when we set the prototype chain of Chiese, we replaced Person. prototype with Chiese. prototype. Therefore, the Chiese. prototype. constructor is Person. We also need to add the following code

The Code is as follows:


// You do not need to elaborate on the if condition here. Just know Chinese. prototype. constructor = Chinese.
If (Chinese. prototype. constructor = Object. prototype. constructor ){
Chinese. prototype. constructor = Chinese;
}

Complete the Code as follows:

The Code is as follows:


Var Person = function (name ){
This. name = name;
};
Person. prototype = {
GetName: function (){
Return this. name;
}
};

Var Chinese = function (name, nation ){
Person. call (this, name );
This. nation = nation;
};
Var F = function (){};
F. prototype = Person. prototype;
Chinese. prototype = F. prototype;
If (Chinese. prototype. constructor = Object. prototype. constructor ){
Chinese. prototype. constructor = Chinese;
}
Chinese. prototype. getNation = function (){
Return this. nation;
};

Var c = new Chinese ("liyatang", "China ");
Alert (c. getName ());

If you can put the inherited code in a function, it facilitates code reuse. Finally, sort out the Code as follows:

The Code is as follows:


Function extend (subClass, superClass ){
Var F = function (){};
F. prototype = superClass. prototype;
SubClass. prototype = new F ();
SubClass. prototype. constructor = subClass;
SubClass. superclass = superClass. prototype; // Add multiple attributes to the parent class to call the parent class function.
If (superClass. prototype. constructor = Object. prototype. constructor ){
SuperClass. prototype. constructor = superClass;
}
}

Var Person = function (name ){
This. name = name;
};
Person. prototype = {
GetName: function (){
Return this. name;
}
};

Var Chinese = function (name, nation ){
Person. call (this, name );
This. nation = nation;
};
Extend (Chinese, Person );
Chinese. prototype. getNation = function (){
Return this. nation;
};

Var c = new Chinese ("liyatang", "China ");
Alert (c. getName ());

Post-publication modification:

In my comments on the first floor, I have a new view on the extend function. Two methods were proposed in the previous discussion about how to set the prototype chain.

The Code is as follows:


// First
// Chinese. prototype = new Person ();
// Type 2
// Var F = function (){};
// F. prototype = Person. prototype;
// Chinese. prototype = F. prototype;

Although the second method reduces the way to call the constructor of the parent class, the Person is used in the design of the Chinese class. call (this, name); the constructor of the parent class is also called.

However, the first method can reduce the number of persons. call (this, name) in Chinese. this part of code is often forgotten in subclass. Put this function code in extend. Write only

Chinese. prototype = new Person (); achieves the same purpose: the coupling is not strong.

However, it is forgotten that Chinese. prototype = new Person (); is written in this way. The answer is no! Obviously, new Person () needs to pass a name parameter. We cannot do this in the extend function, so we have to call the constructor of the parent class in the Chinese class. This is also in line with the object-oriented approach.

Therefore, we recommend the second method.

For the first time, I wrote a technical article in this way, which is basically based on my own ideas. It is inevitable that there will be some unconsidered places and unclear explanations. I hope you can leave a message for feedback. Thank you.

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.