构造函数/原型链/组合/寄生继承

JavaScript继承机制: JavaScript是基于原型链继承的语言,当访问一个属性或者方法的时候,js会沿着原型链依次往上寻找,直到找到相关的值,或者查找到Object.proto === null, 返回undefined值。

有时候,可能需要我们自己去实现类之间的继承,下面是几种继承方法,从上往下,继承方式呈逐渐优化趋势。

父函数和子函数

// 父函数
function Person(sex) {
    this.sex = sex
    console.log(count++)
}
// 父函数原型链方法
Person.prototype.showSex = function () {
    console.log(this.sex)
}
// 子函数
function People(name, age) {
    this.name = name
    this.age = age
}
// 子函数原型链方法
People.prototype.sayHi = function () {
    console.log(`hi~, I am a ${this.sex === 'femal' ? 'girl': 'boy'} my name is ${this.name}, and I am ${this.age} years old`)
}

构造函数继承

function People(name, age) {
    this.name = name
    this.age = age
    Person.call(this, 'femal')
}

不能继承父类的原型链方法,只能实现构造函数的继承

原型链继承

Person.prototype = new Person('femail')
// 添加子函数原型链方法
People.prototype.sayHi = function () {
    console.log(`hi~, I am a ${this.sex === 'femal' ? 'girl': 'boy'} my name is ${this.name}, and I am ${this.age} years old`)
}

只能继承原型链上的继承,父类构造函数里的数据会丢失掉

组合继承

// 继承父类构造函数
function People(name, age) {
    this.name = name
    this.age = age
    Person.call(this, 'femal')
}
// 继承父类原型链
Person.prototype = new Person('femail')
// 添加子函数原型链方法
People.prototype.sayHi = function () {
    console.log(`hi~, I am a ${this.sex === 'femal' ? 'girl': 'boy'} my name is ${this.name}, and I am ${this.age} years old`)
}

同是继承了父类的构造函数和原型链,但是父类的构造函数实例化了两次,造成了不必要的消耗

寄生式继承

// 寄生式继承,通过一个中间值,实现子类原型对象向父类原型对象的指向
// supClass:Constructor 父类
// subClass: Constructor 子类
function inherite(supClass, subClass) {
    let prop = Object.create(supClass).prototype
    prop.constructor = subClass
    subClass.prototype = prop
}

// 子类,完成构造函数的继承
function People(name, age) {
    this.name = name
    this.age = age
    Person.call(this, 'femal')
}

完美!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值