[JavaScript] super

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

super是一个关键字,用来调用父类的方法。
调用方式有两种,super(...params)super.method(...params)

第一种方式super(...params)
(1)只能用于constructor函数中,用于调用父类的constructor
(2)必须在this被使用之前进行调用,
(3)子类constructor函数中,必须调用super(...params)

第二种方式super.method(...params)
(1)可用于调用父类中的任何给定名字的函数,包括super.constructor(...params)
(2)可在任何子类函数中调用,
(3)static函数只能调用父类的static函数,实例函数只能调用父类的实例函数

class T1 {
    constructor(...args) {
        // can't call `super` in base-class constructor
    }


    static staticMethod1(...args) {
        console.log(this, args);
    }

    instanceMethod1(...args) {
        console.log(this, args);
    }
}

class T2 extends T1 {
    constructor(...args) {
        // 1. can't use `this` before super call
        // 2. must call `super(...args)` in sub-class constructor
        // 3. call constructor with (this=T2's instance), and (params=args)
        super(...args);
    }

    static staticMethod2(...args) {
        // 1. can't call `super(...args)`
        // 2. can only call static method in base-class, super.instanceMethod1===undefined
        // 3. call staticMethod1 with (this=T2), and (params=args)
        super.staticMethod1(...args);
    }

    instanceMethod2(...args) {
        // 1. can't call `super(...args)`
        // 2. can only call instance method in base-class, super.staticMethod1===undefined
        // 3. call instanceMethod1 with (this=T2's instance), and (params=args)
        super.instanceMethod1(...args);
    }
}

let t2 = new T2(1, 2)
T2.staticMethod2(3, 4);
t2.instanceMethod2(5, 6);

注:
super.callsuper.apply,实际上是在调用父类名为callapply的方法。
如果父类没有定义同名方法,则值为undefined

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,768评论 0 9
  • 对象的创建与销毁 Item 1: 使用static工厂方法,而不是构造函数创建对象:仅仅是创建对象的方法,并非Fa...
    孙小磊阅读 2,031评论 0 3
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,129评论 3 11