【前端进阶】类的继承

原型继承

让子类的原型等于父类的实例

  1. 父类私有和公有的属性方法,最后都会变为子类实例公有的
  2. 原型继承不会将父类的属性方法拷贝给子类,而是让子类通过原型链查找
// 父类
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)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值