首页 > 代码库 > (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)基于原型的类继承