Home > Article > Web Front-end > Detailed explanation of JavaScript inheritance method (3)
This article continues to explain the JavaScript inheritance method in detail, mainly sharing it with you in the form of code, hoping to help everyone.
1. Inherit tool function three
/** * @param {Function} subCls * @param {Function} superCls */ function extend(subCls,superCls) { subCls.prototype = new superCls(); }
parent class and write it in prototype mode, that is, attributes and methods are all hung on the prototype.
/** * 父类Person */ function Person(){} Person.prototype.nationality = 'China'; Person.prototype.getNationality = function() {return this.nationality;} Person.prototype.setNationality = function(n) { this.nationality = n;}
Subclass inheritance and parent class
function Man() {} extend(Man,Person);
After inheriting the properties and methods of the parent class, then add the subclass’s own properties. The method
Man.prototype.name = 'jack'; Man.prototype.getName = function() { return this.name;} Man.prototype.setName = function(n) { this.name=n;}
is tested as follows,
var m = new Man(); console.log(m); console.log(m instanceof Person);
You can see this way of writing classes, and the inheritance method completely uses the prototype mechanism.
2, inherit tool function four
This method is currently more popular, and the development of the 51ditu website is based on this model.
/** * @param {Function} subCls 子类 * @param {Function} superCls 父类 */ function extend(subCls,superCls) { //暂存子类原型 var sbp = subCls.prototype; //重写子类原型--原型继承 subCls.prototype = new superCls(); //重写后一定要将constructor指回subCls subCls.prototype.constructor = subCls; //还原子类原型 for(var atr in sbp) { subCls.prototype[atr] = sbp[atr]; } //暂存父类 subCls.supr = superCls; }
Write the class according to the constructor + prototype method, that is, the attributes are hung on this and the methods are hung on prototype.
/** * 父类Person */ function Person(nationality){ this.nationality = nationality; } Person.prototype.getNationality = function() {return this.nationality;} Person.prototype.setNationality = function(n) { this.nationality = n;} /** * 子类Man */ function Man(nationality,name) { Man.supr.call(this,nationality); //很重要的一句,调用父类构造器 this.name = name; } Man.prototype.getName = function() {return this.name;} Man.prototype.setName = function(n) {this.name=n;}
Note that in the subclass Man, the call to the parent class constructor to be displayed has completed copying the properties/fields of the parent class.
extend call, create an instance of Man
extend(Man,Person); var m = new Man('USA','jack'); console.log(m) ;m.setName('lily'); console.log(m.name);
The above is the detailed content of Detailed explanation of JavaScript inheritance method (3). For more information, please follow other related articles on the PHP Chinese website!