JavaScript 实现继承的5种方法(类+构造函数)

组合继承(类与类的方法)

详解JS继承,从原理入手到 五种js 实现继承方式

  • 通过构造函数(继承父类属性)+原型对象(父类方法)

通过构造函数继承(继承父类属性)

  function Parent(name) {
    this.name = name; // 实例基本属性 (该属性,强调私有,不共享)
    this.arr = [1]; // (该属性,强调私有)
}
function Child(name, like) {
    Parent.call(this, name, like) // 核⼼ 第一个参数是this现在指向哪里+name(父函数的参数)
    this.like = like;//孩子可以添加自己的属性
}`

通过原型对象(继承父类方法)

Parent.prototype.say = function () { // --- 将需要复⽤、共享的⽅法定义在⽗类原型上
    console.log('hello')
}

Child.prototype = new Parent() // 核⼼ 第⼀次
Child.prototype.constructor = Child // 修正constructor指向

在这里插入图片描述

组合继承优化

// 核⼼ 通过创建中间对象,⼦类原型和⽗类原型,就会隔离开。不是同⼀个啦,有效避免了⽅式4的缺点。
Child.prototype = Object.create(Parent.prototype)
// 这⾥是修复构造函数指向的代码
Child.prototype.constructor = Child

在这里插入图片描述

es6通过类继承

在这里插入图片描述
super必须放到this之前

    class Parent {
      constructor(name) {
        this.name = name;
      }
      getName() {}
    }
 
    class Child extends Parent {
      constructor(name, age) {
        super(name);
        this.age = age;
      }
      getAge() {}
    }
    let person = new Child('Demi', 24)
    console.log(person) // {name: 'Demi', age: 24}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值