美文网首页JavaScript
[JavaScript] super

[JavaScript] super

作者: 何幻 | 来源:发表于2016-09-18 16:13 被阅读84次

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

相关文章

  • [JavaScript] super

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/R...

  • Super, super, super, super happy

    Parent diaries for 137th days weather:sunny Wed...

  • es6方法简写与super关键字

    super关键字表示原型对象,只能用在对象的方法之中。而目前,只有对象方法的简写法可以让 JavaScript 引...

  • Super, super, super, super fun d

    亲子日记第136天 天气:晴 星期二 今天是周二,超级超级超级超级超级超级开心的一天٩(๑^o...

  • Class中的super简析

    super当作函数使用 super()执行父类的构造函数 super() 返回的是子类的实例,即 super 内部...

  • reactES6写法

    注意: super()是为了使用this,必须在使用this之前声明super(); super(props)这个...

  • JAVA面试题

    Q:super()与 this()的区别? A:This():当前类的对象,super 父类对象。 Super()...

  • iOS - super | super | super clas

    super 是编译器的指示符,不是指针,只是一个标识符,代表调用父类的方法,调用者还是自己本身 superclas...

  • super

    super关键字的使用 super理解为:父类的 super可以用来调用:属性、方法、构造器 super的使用:(...

  • Java 泛型 <? super T> 中 supe

    Java 泛型 中 super 怎么 理解?与 extends 有何不同? super只能...

网友评论

    本文标题:[JavaScript] super

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