js 继承父类的属性和方法

文章讲述了ES6中的`extends`继承机制,以及与之前使用构造函数和原型对象(组合继承)的对比,展示了如何在类中实现子类继承父类的属性和方法。
摘要由CSDN通过智能技术生成

1.ES6之后通过extends继承父类的属性和方法。

    // 父类
    class Parent {
      constructor(name, age, weight) {
        this.name = name
        this.age = age
        this.weight = weight
      }
      work() {
        console.log('parent can work.');
      }
    }
    let papa = new Parent('Bob', 50)
    papa.work()// parent can work.
    console.log(papa.name);// Bob
    console.log(papa.age);//0

    //子类
    class Son extends Parent {
      constructor(name, age, weight, height) {
        super(name, age, weight)
        this.name = name
        this.height = height
      }
      study() {
        console.log('No pain, no gain.');
      }
    }
    let child = new Son('Tommy', 12, 40, 155)
    child.work()   //parent can work. //子类继承了父类的方法
    child.study() //No pain, no gain. //子类调用了自己的方法
    console.log(child.weight);//40 //继承了父类的weight属性
    console.log(child.name);//Tommy  

2.ES6前使用构造函数+原型对象来实现继承,也称为组合继承

 //父类
    function Parent(name, age) {
      this.name = name
      this.age = age
    }
    Parent.prototype.work = function () {  //父类上的一个方法
      console.log('parent can work');
    }

    //子类
    function Child(name, age) {
      Parent.call(this, name, age)  //call方法改变了this的指向(指向了son),也调用了Parent构造函数
    }

    //继承父类的方法
    Child.prototype = new Parent()
    Child.prototype.constructor = Child

    let son = new Child('tommy', 12)
    // console.log(son.name);// tommy
    // console.log(son); //Child {name: 'tommy', age: 12} //拥有了父类的属性

    son.work()//parent can work //继承到了父类的方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值