js 原型链及其继承

父类函数

function Father(param){
    this.age = param || 18
}
Father.prototype.say = function () {
    console.log('father say')
}

1:原型链继承(不推荐)

function Child () {}
Child.prototype = new Father()
// 缺点 :
1 无法向父类构造函数传参; 
2 父类的所有属性被共享

2:构造函数继承(不推荐)

function Child(name){
    Father.call(this)
    this.name = name
}
var c = new Child('c')
c.name // 'c'
c.age // 18
c instanceof Child // true
c instanceof Father // false
// 优点
1 可以给父类传参
2 避免了共享属性
// 缺点
1 子类的实例,不是父类的实例
2 方法都在构造函数中创建,每次创建实例都会创建一次方法

3:组合继承(推荐)

function Child(age, name) {
    Father.call(this, age)
    this.name = name
}

Child.prototype = new Father()
Child.prototype.constructor = Child

let jon = new Child(18, 'jon')
jon.age // 18
jon.name // jon

let flash = new Child(22, 'flash')
flash.age // 22
flash.name // flash

jon.age // 18

jon instanceof Father// true
jon instanceof Child// true
flash instanceof Father// true
flash instanceof Child// true

4:寄生组合继承(最佳)

5:ES6 extends (最佳)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值