寄生组合式继承
组合继承是Javascript最常用的继承模式, 但是以为调用了两次超类的构造函数,所以还有不足。而寄生组合式继承则解决了这个问题。实现如下:
function inheritPrototype(subType, superType) { var prototype = Object.create(superType.prototype); //创建原型对象 prototype.constructor = subType; //将constructor指向subType subType.prototype = prototype; //从写subType的原型对象 }
使用如下:
function SuperType(name) { this.name = name; this.colors = ["red", "blue", "green"]; } SuperType.prototype.getSuperColors = function () { console.log(this.colors); } function SubType(name, age) { SuperType.call(this, name); this.age = age; } inheritPrototype(SubType, SuperType); var instance1 = new SubType("Nicholas", 29); instance1.getSuperColors(); console.log(instance1.name); console.log(instance1.age);
备注: 例子及截图均来自《JAVASCRIPT高级程序设计:第3版》