js继承的简单理解

本文深入探讨了JavaScript中的构造函数、原型继承、组合继承和寄生组合继承四种继承模式。通过示例代码详细解释了每种模式的工作原理、优缺点,特别关注了如何处理引用属性的共享问题以及如何实现方法的复用。同时,文章还展示了如何在实际编程中应用这些继承技术,以提高代码的组织和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

## 构造函数
```javascript
// 构造方法创建实例
    function Parent(name, age) {
      this.name = name
      this.age = age
      this.getName = function () {
        alert(this.name)
      }
    }

    class Parent {
      constructor(name, age) {
        this.name = name
        this.age = age
      }
      getName() {
        alert(this.name)
      }
    }
原型继承
    把父类的实例作为子类的原型
    缺点:子类的实例共享了父类构造函数的引用属性   不能传参
    var parent = {
      name: "lele",
      hobby: ['a', 'b', 'c', 'l', 'w', 'l', 'o'],
      age: 9999
    }

    var children = Object.create(parent)
    children.name = 'lllll'
    children.age = 055
    children.hobby.push("aaa")
    console.log(children);
    console.log(parent);

    组合继承
    在子函数中运行父函数,但是要利用call把this改变一下,
    再在子函数的prototype里面new Father() ,使Father的原型中的方法也得到继承,最后改变Son的原型中的constructor

    缺点:调用了两次父类的构造函数,造成了不必要的消耗,父类方法可以复用
    优点可传参,不共享父类引用属性
    function Parent(name) {
      this.name = name
      this.getName = function () {
        alert(this.name)
      }
    }

    function Child(name, age) {
      Parent.call(this, name)
      this.age = age
    }
    Child.prototype = new Parent()
    Child.prototype.constructor = Child
    var a = new Child('lelle', 222)
    a.getName()
    寄生组合继承
    function Parent(name) {
      this.name = name
      this.hobby = ['a', 'adsfs', 1111, 5555555555]
    }
    Parent.prototype.getName = function () {
      alert(`${this.name},${this.hobby}`)
    }
    function child(name, age) {
      Parent.call(this, name)
      this.age = age
    }
    child.prototype = Object.create(Parent.prototype)
    child.prototype.constructor = child
    var a = new child('name', 99999999)
    a.hobby.push('lllllllll')
    a.getName()
    console.log(Parent);

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值