JavaScript super

文章介绍了JavaScript中的super关键字,它用于在继承场景下访问父类的属性和方法。文章通过示例展示了super在子类构造函数中的使用,以及如何在子类中调用父类的方法。还提到了在对象间方法复用的情况,并强调了在子类构造器中必须先调用super的重要性。
摘要由CSDN通过智能技术生成
(在人生的道路上,当你的期望一个个落空的时候,你也要坚定,要沉着。——朗费罗)

在这里插入图片描述

super

super 关键字用于访问对象字面量或类的原型(Prototype)上的属性,或调用父类的构造函数。
MDN super链接

super的常见用法

  1. 继承
class Animal {

  constructor(name, color) {
    this.name = name;
    this.color = color;
  }

  getAnimal () {
    return this.name + this.color;
  }

}

class Cat extends Animal {

  constructor(name, color) {
    super();
    this.name = name;
    this.color = color;
  }

}

const cat = new Cat('橘猫', '橙色');
console.log(cat.getAnimal()); // 橘猫橙色
  1. 指定调用父类方法
    这种场景通常是子类覆盖了父类的方法,但依然有调用父类方法的场景
class Animal {

  constructor(name, color) {
    this.name = name;
    this.color = color;
  }

  getAnimal () {
    return this.name + this.color;
  }

}

class Cat extends Animal {

  constructor(name, color) {
    super();
    this.name = name;
    this.color = color;
  }

  getAnimal () {
    return '子类方法';
  }

  getParentAnimal () {
    return super.getAnimal();
  }

}

const cat = new Cat('橘猫', '橙色');
console.log(cat.getAnimal()); // 子类方法
console.log(cat.getParentAnimal()); // 橘猫橙色
  1. 对象间方法复用
const obj1 = {
  method1() {
    console.log('method 1');
  }
}
const obj2 = {
  method2() {
    super.method1();
  }
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"

注意

需要注意的是,如果子类构造器中this访问出现super之前,就会造成this引用的相关父类状态成员没有完成初始化,所以super一定要在构造器中首先调用。这是ES6的规范,必须先初始化父类才能再加载子类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值