JS Super 关键字详解

JS Super 关键字详解

JS Super 关键字详解

在JavaScript中,super关键字是一个非常重要且常用的关键字,用于引用父类的属性和方法。在子类构造函数中,super()方法用于调用父类的构造函数。本文将详细解释super关键字的用法和示例。

使用 super 访问父类属性和方法

在JavaScript中,我们可以使用super关键字来访问父类的属性和方法。下面是一个简单的示例,演示了如何使用super来访问父类的属性和方法:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`{this.name} makes a noise`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  speak() {
    super.speak();
    console.log(`{this.name} is barking`);
  }
}

const myDog = new Dog('Buddy', 'Golden Retriever');
myDog.speak();

在上面的示例中,我们定义了一个Animal类和一个Dog类。Dog类继承了Animal类。在Dog类的构造函数中,我们调用了super(name)来调用父类Animal的构造函数,并传递了name参数。在Dog类的speak方法中,我们首先调用super.speak()来调用父类Animalspeak方法,然后再输出狗的吠叫声。

当我们运行上面的代码时,将会输出以下结果:

Buddy makes a noise
Buddy is barking

使用 super() 指向父类构造函数

除了可以使用super关键字来访问父类的方法和属性之外,我们还可以使用super()来指向父类的构造函数。下面是一个示例,演示了如何在子类的构造函数中调用父类的构造函数:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  getInfo() {
    console.log(`{this.name} is{this.age} years old`);
  }
}

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }
}

const newStudent = new Student('Alice', 20, 'A');
newStudent.getInfo();

在上面的示例中,我们定义了一个Person类和一个Student类。Student类继承了Person类。在Student类的构造函数中,我们调用了super(name, age)来调用父类Person的构造函数,并传递了nameage参数。这样子类Student就可以继承父类Person的属性nameage。当我们创建一个新的学生newStudent并调用getInfo()方法时,将会输出以下结果:

Alice is 20 years old

不使用 super 的限制

在JavaScript中,如果一个子类想要使用this关键字,那么它必须在调用super之后才能使用this。否则会抛出一个ReferenceError的错误。下面是一个示例,演示了不正确使用this关键字的情况:

class Parent {
  constructor() {
    this.parentProperty = 'I am from Parent class';
  }
}

class Child extends Parent {
  constructor() {
    console.log(this.parentProperty); // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
    super();
  }
}

const child = new Child();

在上面的示例中,我们定义了一个Parent类和一个Child类。在Child类的构造函数中,我们试图在调用super()之前使用this.parentProperty来访问父类的属性,但是由于没有先调用super(),所以会抛出一个ReferenceError的错误。

总结

在JavaScript中,super关键字是一个非常强大和常用的关键字,用于访问父类的属性和方法以及调用父类的构造函数。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程