寄生组合式继承
function inherObj(o){ function F(){} F.prototype=o; return new F(); } function inherPro(SubClass,SuperClass){ var p = inherObj(SuperClass.prototype);
//这一步是为了把构造函数指向SubClass实际对象 p.constructor = SubClass; SubClass.prototype=p; } var book={ name:'js book', alikeBook:['css book','html book'] }; function SuperClass(name){ this.name=name; this.colors=['red','blue','green']; } SuperClass.prototype.getName=function(){console.log(this.name)}; function SubClass(name,time){ SuperClass.call(this,name); this.time=time; } inherPro(SubClass, SuperClass);//这一步就是用SubClass的原型去继承SuperClass的原型,继承的核心代码 SubClass.prototype.getTime=function(){ console.log(this.time); }
//如果子类想重写父类,那就自己覆盖父类同名属性
// SubClass.prototype.getName = function () { console.log(this.name,'重写') };
var ins1 = new SubClass('js book', 2014); var ins2 = new SubClass('css book',2013);
与java逻辑相同
就是继承父类,然后子类可以扩展父类
https://www.cnblogs.com/aaronchu/p/6168378.html