super

作者: 小麻烦爱学习 | 来源:发表于2020-03-30 18:07 被阅读0次

super这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。

第一种情况,super作为函数调用时,代表父类的构造函数。
第二种情况,super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。
class A {
constructor() {
this.x = 1;
}
print() {
console.log(this.x);
}
}

class B extends A {
constructor() {
super();
this.x = 2;
}
m() {
super.print();//相当于super.print.call(this)
}
}

let b = new B();
b.m() // 2

由于this指向子类实例,所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性。

class A {
constructor() {
this.x = 1;
}
}

class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined,相当于A.prototype.x
console.log(this.x); // 3
}
}

let b = new B();
https://es6.ruanyifeng.com/#docs/class-extends

相关文章

  • Super, super, super, super happy

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

  • 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只能...

  • Wildcards with super

    What is Wildcards with super The quizzical phrase ? super...

  • Java中Super()与this()

    Java中Super()与this() super指父类,this指当前对象super()与this()都必须在构...

网友评论

      本文标题:super

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