继承的实现

本文深入探讨了JavaScript中的类继承,包括ES6的class语法和传统的原型链实现方式。通过示例展示了如何使用constructor、super关键字进行实例化和调用父类方法。同时,还介绍了借用构造函数、组合继承、原型式继承、寄生式继承以及寄生组合式继承等继承模式,分析了各自的优缺点。最后提到了理想的寄生组合式继承,它能有效避免多次调用父构造函数的问题,保持原型链的完整。
摘要由CSDN通过智能技术生成

类继承的时候可以继承属性和方法,

//ES6语法,class方法,同java
class Person{
	constructor(name){
		this.name = name;
	}
	drink(){
		console.log('drink')
	}
}
class Student extends Person{//使用extends继承
	constructor(name,score){
		super(name)//使用super关键字执行父类的构造函数
		this.score = score
	}
}
class Teacher extends Person{//使用extends继承
	constructor(name,sub){
		super(name)//使用super调用父类构造函数
		this.sub= sub
	}
}
const student = new Student('amy',99)
student.drink()//调用父类方法
//原型链方法
//优点:简单
//缺点:属性被实例共享,不能向父类传递参数
function Parent(){
	this.name = 'Parent'
	this.play= [1,2,3]
}

function Child(){
	this.type = 'Child'
}
Child.prototype = new Parent()//在链上,但当使用同一个对象声明两个实例时,修改其中一个,另一个也修改
const s1 = new Child()
const s2 = new Child()
s1.play.push(4)
//此时s1、s2的play属性都是[1,2,3,4]
//借用构造函数
//优点:避免了共享,可以向父类传递参数
//缺点:方法在构造函数中定义,创建实例都会创建一遍方法
function Parent(){
	this.name = 'Parent'
}

function Child(){
	Parent.call(this)
	this.type = 'Child'
}
//组合继承
//最常用,
//调用了两次父亲的构造函数
function Parent(){}
function Child(){
	Parent.call(tihs)
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;

//原型式继承(Object.create())
//优点:简单
//缺点:属性被实例共享
function CreateObj(o){
	function F(){}
	F.prototype = o;
	return new F();
}
//寄生式继承
//缺点:方法在构造函数中定义,创建实例都会创建一遍方法
function createObj(o){
	var clone = Object.create(o);
	clone.sayName = function(){}
	return clone;
}
//寄生组合式继承(最理想)
//优点高效率,只调用一次父构造函数,原型链不变
function Parent(){}
function Child(){
	Parent.call(tihs)
}
var F= function(){}
F.prototype = Parent.prototype;
Child.prototype = new F()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值