首页 > 代码库 > (2)基于原型的类继承
(2)基于原型的类继承
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) Dog类继承Animal类,这种继承属于原型继承,那就是说Dog的原型里面拥有Animal类的实例
2 version 2 类库添加继承
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();
可以仔细看这段代码
if(parent){ var subClass = function(){}; subClass.prototype = parent.prototype; klass.prototype = new subClass(); }
再次将Animal这个function传回去,新建一个局部的subClass的原型指向Animal的原型,再将klass的原型指向subClass的实例,防止了原型污染
(2)基于原型的类继承
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。