var timen = 0
//原型式继承
function inheritObject(o){
//过度类
function F(){};
//过度类继承父类
F.prototype = o;
//返回过度类的一个实例
return new F();
}
/**
* 寄生式继承
*
*/
function inheritPrototype(subClass,superClass){
console.log('time:',++timen)
//复制一份父类的原型副本保存在变量中
let p = inheritObject(superClass.prototype);
//修正因为重写子类原型导致子类的constructor 属性被修改
p.constructor =subClass;
//设置子类的原型
subClass.prototype=p;
}
//d定义父类
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
}
//寄生式继承父类原型
inheritPrototype(SubClass,SuperClass);
//子类新增原型方法
SubClass.prototype.getTime=function(){
console.log(this.time);
}
//创建两个测试方法
let instance1 = new SubClass("js book",2014);
let instance2 = new SubClass('css book',2013);
instance1.colors.push("black")
console.log('isntance1',instance1);
console.log('2',instance2);
instance1.getTime();
instance2.getTime();
js 原型式继承++------寄生组合式继承
最新推荐文章于 2024-11-11 19:29:13 发布