Implementation of prototype inheritance
1 Simplified version
function Superclass () {...} function Subclass () {...} Subclass.prototype=new superclass ();
Subclass.prototype.constructor=subclass;
Note: This method is correct in most cases, but sometimes the problem occurs. If function superclass (name) {this.name=name.touppercase ()}, an error occurs when calling new superclass ().
2 Comparison of a generic implementation of a prototype inheritance
//The child of the function does not inherit the custom property of parent
functionInherite (child,parent) {varf=function(){}; //F share a prototype with parentF.prototype=Parent.prototype; //Child 's prototype is an instance of FChild.prototype=NewF (); Child.prototype.constructor=Child ;}functionSuperclass (name) { This. name=name;}functionSubclass (Name,age) {Superclass.call ( This, name); This. age=Age ;} Inherate (subclass,superclass);
Benefit: Avoid creating an instance of a parent class (superclass), and avoid side effects of some parent constructors
3 Clean prototype inheritance
function superclass () {} function Subclass () {}subclass.prototype=object.create (superclass.prototype);
Subclass.prototype.constructor=subclass;
Note: the Object.create () method is supported only by some browsers
The inheritance of JavaScript