一、原型继承
// 父类
function Persion(name,age){
this.name = name;
this.age = age;
}
// 父类的原型对象属性
Persion.prototype.id = 110;
// 子类
function Boy(sex){
this.sex = sex;
}
// 继承实现
Boy.prototype = new Persion('杨晋',25);
var b = new Boy();
console.log(b.name)// 杨晋
这种原型继承的特点:既继承了父类的模板,又继承了父类的原型对象。
优点:继承了父类的模板,又继承了父类的原型对象
缺点:父类实例传参,不是子类实例化传参,不符合常规语言的写法
二、类继承(借用构造函数的方式继承)
// 父类
function Persion(name,age){
this.name = name;
this.age = age;
}
// 父类的原型对象属性
Persion.prototype.id = 110;
// 子类
function Boy(name,age,sex){
//call apply 实现继承
Persion.call(this,name,age);
this.sex = sex;
}
var b = new Boy('杨晋',25,'女');
console.log(b.name)// 杨晋
console.log(b.id)//undinfind 父类的原型对象并没有继承
这种原型继承的特点:继承了父类的模板,不继承了父类的原型对象。
优点:方便了子类实例传参
缺点:不继承了父类的原型对象
三、混合继承(原型继承和类继承)
// 父类
function Persion(name,age){
this.name = name;
this.age = age;
}
// 父类的原型对象属性
Persion.prototype.id = 110;
// 子类
function Boy(name,age,sex){
//call apply 实现继承
Persion.call(this,name,age);
this.sex = sex;
}
// 原型继承实现 参数为空 代表 父类的实例和父类的原型对象的关系了
Boy.prototype = new Persion();
var b = new Boy('杨晋',25,'男');
console.log(b.name)// 杨晋
console.log(b.id)//110
这种原型继承的特点:既继承了父类的模板,又继承了父类的原型对象。
优点:方便了子类实例传参
缺点:Boy.pertotype = new Persion() 函数又实例一次,函数内部变量又重复实例一次,大程序时候会消耗性能。