//js中最常用的继承方式--组合继承 function Super(name){ this.name = name; this.colors = ["red","blue","green"]; } Super.prototype.sayName = function(){ console.log(this.name); } function Sub(name){ //继承了属性 Super.call(this,name); } //继承了方法 Sub.prototype = new Super(); var sub1 = new Sub("Nick"); sub1.colors.push("black"); console.log(sub1.colors); //(4) ["red", "blue", "green", "black"] sub1.sayName(); //Nick var sub2 = new Sub("Lucy"); console.log(sub2.colors); //(3) ["red", "blue", "green"] sub2.sayName(); //Lucy
组合继承避免了原型链和借用构造函数的缺陷,融合了它们的优点,成为js中最常用的继承模式。
//返回的都是true console.log(sub1 instanceof Object); console.log(sub1 instanceof Super); console.log(sub1 instanceof Sub); console.log(Object.prototype.isPrototypeOf(sub2)); console.log(Super.prototype.isPrototypeOf(sub2)); console.log(Sub.prototype.isPrototypeOf(sub2));
并且instanceof和isPrototypeOf()方法也都能正确的识别基于组合继承创建的对象。