javascript中的继承-组合继承
连续两篇水文(javascript中的继承-原型链,javascript中的继承-借用构造函数),这种行为完全是充数,这里结合两者的优点介绍组合继承模式:
function SuperType(name){ this.name=name; this.friends=["gay1","gay2"]; } SuperType.prototype.sayName=function(){ alert(this.name); }; function SubType(name,age){ SuperType.call(this,name); this.age=age; } SubType.prototype=new SuperType(); SubType.prototype.constructor=SubType; SubType.prototype.sayAge=function(){ alert(this.age); }; var instance1=new SubType("nUll",25); var instance2=new SubType("mywei",25); instance1.friends.push("gay3"); alert(instance1.friends); //gay1,gay2,gay3 instance1.sayName(); //nUll instance1.sayAge(); //25 alert(instance2.friends); //gay1,gay2 instance2.sayName(); //mywei instance2.sayAge(); //25 alert(instance1 instanceof SuperType); //true alert(SuperType.prototype.isPrototypeOf(instance1)); //true
这里再简单的总结两句:加上我刚才说的那句.我已经说完了.