组合式继承
function super(name){ this.name=name; this.colors=["red","blue","green"] } super.prototype.sayName=function(){ console.log(this.name); }; function sub(name,number){ // 继承属性 super.call(this,name); this.number=number; } //继承方法 sub.prototype=new super();//类似继承,引用,子类改变会影响父类 sub.prototype.sayNum=function(){ console.log(this.number); } var instance1=new sub("cherry",23); instance1.colors.push("magenta"); console.log(instance1.colors);//"red,blue,green,magenta" instance1.sayName();//"cherry" instance1.sayNum();//23 var instance2=new sub("blueberry",25); console.log(instance2.colors);//"red blue,green" instance2.sayName();//"blueberry" instance2.sayNum();//25 //融合了原型链和构造函数的优点
寄生组合式继承
function super(name){ this.name=name; this.colors=["red","blue","green"]; } super.prototype.sayName=function(){ console.log(this.name); } function sub(name,age){ super.call(this,name); this.age=age; } // function inheritPrototype(sub,super){ var prototype=object(super);//创建super原型的一个副本 prototype.constructor=sub;//为创建的副本添加constructor属性 //从而弥补因原型重写而失去的默认的constructor属性 sub.prototype=prototype;//将创建的副本赋值给子类原型 //即可调用inheritPrototype()替换组合继承中为子类原型赋值的语句 } inheritPrototype(sub,super); sub.prototype.sayAge=function(){ console.log(this.age); }
原型链继承即将一个对象的实例赋值给另一对象的原型实现继承
拷贝继承
修复类似继承:借助中间类实现
var a={ name:'roy' } var b=cloneobj(a); b.name='richard'; alert(a.name); alert(b.name); function cloneobj(obj){//原型继承 var f=function(){};//中间子类 f.prototype=obj; return new f(); } //拷贝继承:比较通用的方式,有无new都可以用 //类式继承:new 构造函数 //原型继承:无new对象