【前端进阶】类的继承
原型继承
让子类的原型等于父类的实例
- 父类私有和公有的属性方法,最后都会变为子类实例公有的
- 原型继承不会将父类的属性方法拷贝给子类,而是让子类通过原型链查找
// 父类
function Parent(){
this.x= '父类'
}
Parent.prototype.getX = function getX(){
return this.x;
}
// 子类
function Child(){
this.y= '子类'
}
Child.prototype = new Parent; // 原型继承
Child.prototype.getY = function getY(){
return this.y;
}
// 子类实例
let a = new Child();
console.log(a)
call 继承
只能继承父类中私有的属性和方法,不能继承共有的
// 父类
function Parent(){
this.x= '父类'
}
Parent.prototype.getX = function getX(){
return this.x;
}
// 子类
function Child(){
// 把父类当做普通函数执行,父类原型链上的属性方法就和它没有关系了
// this指向new创建的实例,相当于为实例添加了一个私有属性x
Parent.call(this)
this.y= '子类'
}
Child.prototype.getY = function getY(){
return this.y;
}
// 子类实例
let a = new Child();
console.log(a)
寄生组合继承(另类原型继承+call继承)
// 父类
function Parent(){
this.x= '父类'
}
Parent.prototype.getX = function getX(){
return this.x;
}
// 子类
function Child(){
Parent.call(this)
this.y= '子类'
}
// Child.prototype.__proto__ = Parent.prototype
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.getY = function getY(){
return this.y;
}
// 子类实例
let a = new Child();
console.log(a)