您的位置:首页 > Web前端 > JavaScript

Javascript继承6:终极继承者----寄生组合式继承

2018-10-02 17:49 507 查看
/*
* 寄生式继承依托于原型继承,原型继承又与类式继承想象。
* 即: 原型与构造函数的组合继承
* 寄生式继承  继承原型
* 传递参数 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);
}
// test
var 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()              // Vue
child2.getTime()              // 2017

设计模式中的经典笔录

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: