3. Inheritance tool function 3
View sourceprint? 1 /**
2 * @ param {Function} subCls
3 * @ param {Function} superCls
4 */
5 function extend (subCls, superCls ){
6 subCls. prototype = new superCls ();
7}
Parent class, written in prototype mode, that is, attributes and methods are attached to the prototype.
View sourceprint? 1 /**
2 * parent class Person
3 */
4 function Person (){}
5 Person. prototype. nationality = China;
6 Person. prototype. getNationality = function () {return this. nationality ;}
7 Person. prototype. setNationality = function (n) {this. nationality = n ;}
Subclass inheritance and parent class
View sourceprint? 1 function Man (){}
2 extend (Man, Person );
After inheriting the attributes and methods of the parent class, add the attributes and methods of the subclass.
View sourceprint? 1 Man. prototype. name = jack;
2 Man. prototype. getName = function () {return this. name ;}
3 Man. prototype. setName = function (n) {this. name = n ;}
The test is as follows,
View sourceprint? 1 var m = new Man ();
2 console. log (m );
3 console. log (m instanceof Person );
We can see that this write class method completely uses the prototype mechanism for inheritance.
4. inherit from tool function 4
This method is currently quite popular, and 51ditu website development follows this mode.
View sourceprint? 01 /**
02 * @ param {Function} subCls subclass
03 * @ param {Function} superCls parent class
04 */
05 function extend (subCls, superCls ){
06 // temporary subclass prototype
07 var systolic = subCls. prototype;
08 // rewrite the subclass prototype-prototype inheritance
09 subCls. prototype = new superCls ();
10 // After rewriting, the constructor must be referred back to subCls
11 subCls. prototype. constructor = subCls;
12 // restore the subclass prototype
13 for (var autoregroup ){
14 subCls. prototype [ASD] = systolic [ASD];
15}
16 // Save the parent class
17 subCls. supr = superCls;
18}
Write classes by constructors + prototype, that is, attributes are mounted on this, and methods are mounted on prototype.
View sourceprint? 01 /**
02 * parent class Person
03 */
04 function Person (nationality ){
05 this. nationality = nationality;
06}
07 Person. prototype. getNationality = function () {return this. nationality ;}
08 Person. prototype. setNationality = function (n) {this. nationality = n ;}
09
10 /**
11 * subclass Man
12 */
13 function Man (nationality, name ){
14 Man. supr. call (this, nationality); // an important sentence that calls the parent class constructor.
15 this. name = name;
16}
17 Man. prototype. getName = function () {return this. name ;}
18 Man. prototype. setName = function (n) {this. name = n ;}
Note that the property/field copy of the parent class has been completed by calling the parent class constructor to be displayed in the subclass Man.
Extend call, create Man instance
View sourceprint? 1 extend (Man, Person );
2 var m = new Man (USA, jack );
3 console. log (m );
4 m. setName (lily );
5 console. log (m. name );