寄生组合继承和类继承

1.寄生组合继承

使用Object.create方法来实现继承

function Father(name,age) {
  this.name = name
  this.age = age
}
Father.prototype.giveMoney = function (money) {
  console.log('父亲给了' + money + '元零花钱');
}
function Child(name, age) {
 // 使用call改变Child中this的指向,指向Father,传入参数name和age
  Father.call(this,name,age)
}
// 使用Object.create来创建新对象,用来接收父构造函数的prototype
Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child

const child = new Child('小明', 12)
console.log(child);
child.giveMoney(36)

 2.类继承

 ES6之后的一般使用class类继承

class Father{
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  giveMoney(money) {
   console.log('父亲给了' + this.name + money + '元零花钱');
  }
  checkScore() {
    console.log('父亲查看了' + this.name + '的成绩是' + this.score + '分');
  }
}
class Child extends Father{
  constructor(name, age ,score) {
     //使用super关键字来继承属性,必须写在首位
    super(name, age)
    this.score = score
  }
  showScore() {
    console.log('给父亲查看成绩');
    //使用super关键字来继承方法
    super.checkScore()
  }
  getMoney(money) {
    //也可以使用this关键字来继承方法
    this.giveMoney(money)
    //super.giveMoney(money)
  }
}

const child = new Child('小红', 14, 99)
console.log(child);
child.showScore()
child.getMoney(100)
child.giveMoney(200) // 直接使用从父类继承的方法

                           

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值