Introduction to JS inheritance

Source: Internet
Author: User

1. Introduction
Inheritance in JS is a very complex topic and is much more complex than any other object-oriented language. In most other object-oriented languages, only one keyword is required to inherit a class. To Inherit public members in JS, a series of measures are required. JS belongs to the original type inheritance. Thanks to this flexibility, we can either use standard class-based inheritance or use more subtle original type inheritance. In JavaScript, it should be clear that all inheritance is carried out through prototype, and JS is inherited based on objects.
2. The most intuitive Inheritance Method
Let us assume that there is now such an inheritance level: a Person base class, containing the name attribute and a getName method; an Author class that inherits the Person class, with its own books attribute and getBooks method. The simplest method of class inheritance is as follows:
 
/* Class Person */
Function Person (name ){
This. name = name;
}

Person. prototype. getName = function (){
Return this. name;
};

/* Class Author */
Function Author (name, books ){
Person. call (this, name); // call the parent class constructor. The second call is the parent class constructor.
This. books = books;
}

Author. prototype = new Person (); // sets the prototype chain to obtain the method of the parent class. The first time the parent class constructor is called
Author. prototype. constructor = Author; // sets the constructor.
Author. prototype. getBooks = function (){
Return this. books;
};
 
The disadvantage of the above Code is that when the Authro object is instantiated, the constructor of the parent class will be called twice, and the object of the parent class needs to be instantiated in the prototype chain, the above code saves a name attribute in the parent class. In fact, this is unnecessary. If there are more inheritance layers and more attributes, the burden will be high. We can improve this. In fact, all we need is the prototype of the parent class. The attributes contained in the parent class are obtained by calling the parent class constructor. In addition, the above Code seems to have little relevance between the parent class and the subclass, so here we add an extend function to the function prototype to explicitly indicate the inheritance level, so we have the original type inheritance below.
3. Original Type inheritance
When talking about the original type inheritance, it is best to forget all your knowledge about classes and instances and think about it only from the perspective of objects. As we mentioned above, JavaScript is inherited based on objects. The prototype attribute of an object actually points to an instantiated object. Therefore, we can think that we do not need to use classes (constructors) to define the structure of objects. We only need to create an object directly. See the following code:
 
/* Extend function to realize original type inheritance */
Var extend = function (obj ){
If (typeof obj! = 'Object '){
Throw new Error ('fatal error: "Object. prototype. extend" expects a object ');
}

Var F = function () {}; // create an intermediate function object
F. prototype = obj; // set its prototype object to object

Return new F (); // return the instantiated F
};

/* Parent literal object */
Var Person = {
Init: function (name) {// initialize the function, and set various attributes to replace the role of the constructor.
This. name = name;
},
GetName: function (){
Return this. name;
}
};

/* Subclass object */www.2cto.com
Var author1 = extend (Person); // inherits the Person
Author1.init ('author ');
Alert (author1.getName (); // output author
Author1.books = 'xxx'; // set your own attributes
Author1.getBooks = function (){
Return this. books;
};
Alert (author1.getBooks (); // output xxx
 
The above code implements inheritance through the Global extend function, and then adds members as needed. The init function of the parent class acts as the role of the constructor, essentially, it is equivalent to directing prototype to an instantiated Object. However, those who get used to the new operator may not get used to the inheritance of this method, including me. In order to make the code more in line with our habits, we have class inheritance.
4. class inheritance
Class inheritance is implemented by simulating the traditional object-oriented language. By adding an extend Function to the Function prototype, the subclass constructor inherits the parent class through the extend Function, at the same time, we set a reference pointing to the parent class object internally, so that we can easily directly call the method of the parent class object. The details are as follows:
 
/* Add an extend function to the function prototype to implement inheritance */
Function. prototype. extend = function (superClass ){
If (typeof superClass! = 'Function '){
Throw new Error ('fatal error: Function. prototype. extend expects a constructor of class ');
}

Var F = function () {}; // create an intermediate function object to obtain the prototype object of the parent class
F. prototype = superClass. prototype; // sets the prototype object.
This. prototype = new F (); // instantiate F, inheriting the attributes and methods in the parent class prototype, without calling the parent class constructor to instantiate irrelevant parent class members
This. prototype. constructor = this; // set the constructor to point to itself.
This. superClass = superClass; // At the same time, add a reference pointing to the parent class constructor to facilitate calling the parent class method or calling the parent class Constructor

Return this;
};


/* Class Person */
Function Person (name ){
This. name = name;
}
Person. prototype. getName = function (){
Return this. name;
};


/* Class Author */
Function Author (name, books ){
Author. superClass. call (this, name );
This. books = books;
}
/*
* The chain call is used here. The following statement is equivalent:
* Author. extend (Person); Author. prototype. getBooks = function (){'''};
*/
Author. extend (Person). prototype. getBooks = function (){
Return this. books;
};
/* Override of methods. The superClass calls the parent class method to obtain basic information, and then calls the subclass method to obtain more special information */
Author. prototype. getName = function (){
Var name = Author. superClass. prototype. getName. call (this );
Return name + ', Author of' + this. getBooks ();
};
 
The Inheritance Method of the above Code should be the most popular Inheritance Method for various frameworks and JS libraries. On the one hand, the constructor is called only once when the object is instantiated, there is no need to save unnecessary attributes of the parent class instantiation. Through the superClass attribute, you can easily call the parent class method to override or enhance the subclass method.
5. Member Expansion
Maybe, sometimes we want to expand a group member to an existing object, so we can save the Members to be expanded in an object, and then traverse and Add. So we can extend the extend function so that it can accept parameters of the object type.
 
Function. prototype. extend = function (superClass ){
If (typeof superClass = 'function') {// class inheritance
Var F = function () {}; // create an intermediate function object to obtain the prototype object of the parent class
F. prototype = superClass. prototype; // sets the prototype object.
This. prototype = new F (); // instantiate F, inheriting the attributes and methods in the parent class prototype, without calling the parent class constructor to instantiate irrelevant parent class members
This. prototype. constructor = this; // set the constructor to point to itself.
This. superClass = superClass; // At the same time, add a reference pointing to the parent class constructor to facilitate calling the parent class method or calling the parent class Constructor
} Else if (typeof superClass === 'object') {// method extension
Var pro = this. prototype;
For (var k in superClass ){
If (! Pro [k]) {// If the prototype object does not have this attribute, copy
Pro [k] = superClass [k];
}
}
} Else {
Throw new Error ('fatal error: "Function. prototype. extend" expects a function or object ');
}

Return this;
};
/* Call Method */
Author. extend ({
SayHello: function (){
Alert ('hello ');
}
}). Extend (classFunction. prototype); // The prototype is also an object, so it can be passed in as a parameter. In this way, the prototype method of other classes is extended, which is similar to multi-inheritance.
 
In the above Code, we have extended the extend function so that it can accept parameters of the object type to implement Member expansion. At the same time, if you do not need to call the parent class constructor, or if you do not want to change the reference to the parent class object, you can pass the prototype of the new constructor. If we have another requirement and only need to extend some methods of passing objects, we can continue to transform our extend function. When the parameter is greater than 2, the following parameters are the attributes to be extended.
In fact, extended extend functions also have some taste of original type inheritance, but we still need to define the constructor of the subclass. From another perspective, extended members also have a taste of Multi-inheritance.

 

From lhgcore. J

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.