1 version 1
var Animal = function(){ this.init(this,arguments); }; //init Animal.prototype.init = function(color){ this.color = color; }; Animal.prototype.breath = function(){ console.log("breath"); }; var Dog = function(){}; Dog.prototype = new Animal(); Dog.prototype.init("white"); Dog.prototype.getColor = function(){ console.log(this.color); }; var dog = new Dog(); dog.breath();//breath dog.getColor();//white
(1) The Dog class inherits the animal class. This inheritance belongs to the prototype inheritance, that is, the dog prototype has an animal class instance.
2 version 2 class library add inheritance
var Class = function(parent){ var klass = function(){ this.init.apply(this,arguments); }; if(parent){ var subClass = function(){}; subClass.prototype = parent.prototype; klass.prototype = new subClass(); } //init klass.prototype.init = function(){}; klass.fn = klass.prototype; klass.fn.parent = klass; //add class property klass.extend = function(obj){ var extended = obj.extended; for(var i in obj){ klass[i] = obj[i]; } if(extended) extended(klass); }; //add prototype property klass.include = function(obj){ var included = obj.included; for(var i in obj){ klass.fn[i] = obj[i]; } if(included) included(klass); }; return klass; }; var Animal = new Class(); Animal.include({ breath:function(){ console.log(‘breath‘); } }); var Cat = new Class(Animal); var tommy = new Cat(); tommy.breath();
You can read this code carefully.
if(parent){ var subClass = function(){}; subClass.prototype = parent.prototype; klass.prototype = new subClass(); }
Upload the animal function again, create a local subclass prototype to point to the animal prototype, and then point the Klass prototype to the subclass instance to prevent prototype pollution.
(2) prototype-based class inheritance