JS的几种继承

本文详细介绍了JavaScript中四种常见的继承实现方式:构造函数继承、原型链继承、组合继承及其优化,以及寄生组合继承。每种方式都有其优缺点,如构造函数继承能传参但方法不可复用,原型链继承则可能导致引用属性共享。组合继承通过结合两者避免了一些问题,但存在重复调用父类构造函数的缺点。寄生组合继承通过Object.create解决了这一问题,成为更完美的继承模式。
摘要由CSDN通过智能技术生成

第一种:构造函数继承

核心思想:使用call()改变子类的this指向父类,使其子类实例拥有父类的属性和方法
代码:

function Person(name){
    this.name = name
    this.hello = function(){
        console.log('hello')
    }
}
Person.prototype.introduce = function(){
    console.log('你好,我叫' + this.name)
}
function Student(name, xh){
    Person.call(this, name)
    this.xh = xh
}
let stu = new Student('张三', 20190345)
console.log(stu)
stu.hello()
stu.introduce()	//报错

优点:
子类构造函数向父类构造函数中传递参数
可以实现多继承(call或者apply多个父类)

缺点:
方法都在构造函数中定义,无法复用
不能继承原型属性/方法,只能继承父类的实例属性和方法

第二种:原型链继承

核心思想:父类实例作为子类的原型
优点:方法复用,服用了父类原型链上的方法
缺点:创建子类实例时,不能向构造函数传参;子类实例共享了父类构造函数的引用属性;

function Parent(name){
	this.name = name || '父亲'
	this.arr = [1]
}

Parent.prototype.say = function(){
	console.log('hello')
}

function Child(like){
	this.like = like
}
Child.prototype = new Parent()
Child.prototype.constructor = Child

第三种:组合继承

代码:

function Parent(name){
	this.name = name
	this.arr = [1]
}
Parent.prototype.say = function(){
	console.log('hello')
}
function Child(name, like){
	Parent.call(this, name)
	this.like = like
}
Child.prototype = new Parent()
Child.prototype.constructor = Child

优点:可以向父类构造函数传参;可以复用父类原型上的方法;不共享父类的引用属性
缺点:两次调用了父类的构造函数,会存在一份多余的父类实例对象

第四种:组合继承优化

代码:

function Parent(name){
	this.name = name
	this.arr = [1]
}
Parent.prototype.say = function(){
	console.log('hello')
}
function Child(name, like){
	Parent.call(this, name)
	this.like = like
}
Child.prototype = Parent.prototype

第五种:寄生组合继承

完美
代码:

function Parent(name){
	this.name = name
	this.arr = [1]
}
Parent.prototype.say = function(){
	console.log('hello')
}
function Child(name, like){
	Parent.call(this, name)
	this.like = like
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值