zoukankan      html  css  js  c++  java
  • ES6---Class继承

    (1)简介

      Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。

      

    上面代码定义了一个Child类,该类通过extends关键字,继承了Parent类的所有属性和方法。
    但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个Parent类。下面,我们在Child内部加上代码。

      

       

    super及this本质:
        子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,
      加上子类自己的实例属性和方法

      如果不调用super方法,子类就得不到this对象。

      ES5 与 ES6继承区别

    ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。
    ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。

      

    (2)子类没有定义constructor构造器方法

      

     (3)在子类的构造函数中,只有调用super之后,才可以使用this关键字

      

       

    案例如下:

      

            class Parent{
                /*父亲:名字、肤色、习惯*/
                constructor(name,color){
                    this.name = name
                    this.color = color
                }
                toString(){
                    return `name:${this.name},color:${this.color}.`
                }
                /*习惯*/
                habit(){
                    console.log(`${this.name} Like to touch the nose`)
                }
            }
            class Child extends Parent{
                constructor(x,y,eyes){
                    super(x,y)/*调用父类的constructor(name,color)肤色和姓继承自父亲*/
                    this.eyes = eyes
                }
                toString(){
                    return super.toString()+`,eyes:${this.eyes}`/*调用父类的toString()*/
                }
            }
            /*父亲*/
            var dad = new Parent('','yellow')
            console.log(dad.toString())
            /*儿子*/
            var child = new Child('','yellow','small eyes')
            console.log(child.toString())

    .

  • 相关阅读:
    linux文件系统
    用户态和内核态
    nginx优化
    平滑升级nginx
    网络--基本概念
    haproxy
    awk
    kvm
    lvs
    自定义不等高cell—storyBoard或xib自定义不等高cell
  • 原文地址:https://www.cnblogs.com/jianxian/p/12343143.html
Copyright © 2011-2022 走看看