/** 寄生式继承依托于原型继承,原型继承又与类式继承想象。* 即: 原型与构造函数的组合继承* 寄生式继承 继承原型* 传递参数 childClass 子类* 传递参数 parentClass 父类*///原型式继承function inheritObj(obj){ //声明一个过渡函数对象 function F(){} //过渡对象的原型继承父对象 F.prototype = obj; //返回过渡对象的一个实例,该实例的原型继承了父对象 return new F();}function inheritPrototype(childClass,parentClass){ //复制一份父类原型副本保存在变量中 var p = inheritObj(parentClass.prototype); //修正因为重写子类原型导致子类的constructor属性被修改 p.constructor = childClass; //设置子类原型 childClass.prototype = p;}// 定义父类function ParentClass(name){ this.name = name; this.books = ['Html'];}//定义父类原型方法ParentClass.prototype.getName = function(){ console.log(this.name);}//定义子类function ChildClass(name,time){ //构造函数是继承 ParentClass.call(this,name); //子类新增属性 this.time = time;}// 寄生式继承父类原型inheritPrototype(ChildClass,ParentClass);//子类新增方法ChildClass.prototype.getTime = function(){ console.log(this.time);}// testvar child1 = new ChildClass('react',2018);var child2 = new ChildClass('vue',2017);child1.books.push('css');console.log(child1.books) // ['Html','css']console.log(child2.books) // ['html']child2.getName() // Vuechild2.getTime() // 2017
设计模式中的经典笔录