美文网首页
用js如何实现继承

用js如何实现继承

作者: 雪中无处寻 | 来源:发表于2020-04-02 12:35 被阅读0次

今天我总结了继承的方式,和大家探讨一下

一、es6中的类继承:

    这种方式使用起来比较简单,也我喜欢的一种方式,它的继承依靠关键字extends,其实这只是一种语法糖,其本质还是原型继承。
    代码如下:

    // es6中的类继承
    class Parents  {
      constructor (name, age) {
        this.name = name
        this.age = age
      }
      toString () {
        console.log(`您的名字是${this.name},您的年龄为:${this.age}`)
      }
    }

    class Son extends Parents {
      constructor (name, age, mheight) {
        super(name, age)
        this.mheight = mheight
      }
      myString () {
        console.log(`您的名字是${this.name},您的年龄为:${this.age}, 身高为${this.mheight}`)
      }
    }
    let son = new Son('小雪', 20, "162cm")
    son.toString() // 您的名字是小雪,您的年龄为:20
    son.myString() // 您的名字是小雪,您的年龄为:20, 身高为162cm

    从结果可以看出Son通过extends既拥有自己的属性mheight和方法myString(),又拥有Parents的属性nameage和方法toString()

二、借助构造函数实现继承:

    function Parent1 () {
      this.name = 'parent1'
    }
    function Child1 () {
      Parent1.call(this)
      this.type = 'child1'
    }
    console.log(new Child1)

    这种继承方式无法无法继承父级原型上的属性和方法

三、 借助原型链实现继承:

    function Parent2 () {
      this.name = 'parent2'
      this.play = '123'
    }
    function Child2 () {
      this.type = 'child2'
    }
    Child2.prototype = new Parent2()
    const s1 = new Child2();
    const s2 = new Child2();
    console.log(s1.play, s2.play)

    由于两个实例对象是同一个对象,所以改变一个的值另一个也会变

四、 组合方式实现继承:

   function Parent5 () {
      this.name = 'parent5'
      this.play = [1, 2, 3]
    }
    function Child5 () {
      Parent5.call(this)
      this.type = 'child5'
    }
    Child5.prototype = Object.create(Parent5.prototype)
    Child5.prototype.constructor = Child5
    const s7 = new Child5()
    const s8 = new Child5()
    s7.play.push(4)
    console.log(s7, s8)
    console.log(s7.constructor)

    这种组合方式继承,既能继承父类的属性,又能独立存在

相关文章

  • 用js如何实现继承

    今天我总结了继承的方式,和大家探讨一下 一、es6中的类继承: 这种方式使用起来比较简单,也我喜欢的一种方式,它的...

  • JS继承的实现的几种方式

    前言 JS作为面向对象的弱类型语言,继承也是非常强大的特性之一,那么如何在JS实现继承呢? JS继承的实现方式 既...

  • 继承方式(6种)1.7

    JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一。那么如何在JS中实现继承呢?让我们拭目以待。 JS继承...

  • js的继承 30

    JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一。那么如何在JS中实现继承呢?让我们拭目以待。 JS继承...

  • JS如何实现继承

    使用原型链 class继承(extends、super)

  • JS中继承的实现

    JS中继承的实现 #prototype (js原型(prototype)实现继承) 全局的Function对象没有...

  • js实现继承的几种方式

    如何实现继承? js中实现继承的方式主要是通过原型链完成的。了解原型链的相关信息可以点这里 javascript中...

  • 前端面试-自测

    JS有哪些手段可以实现继承? 说说JS的闭包? 用纯JS实现,点击一个列表时,输出对应的索引(不能用JQuery哦...

  • js继承

    js继承js 继承-简书 原型链实现集继承 上面的代码实现原型链继承最重要的son.prototype=new f...

  • JS继承问题

    JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一,那么,我们该如何在JS中实现继承呢? 一、公有私有属性...

网友评论

      本文标题:用js如何实现继承

      本文链接:https://www.haomeiwen.com/subject/trotphtx.html