返回

TypeScript 中 this 和 super 的深入探索

前端

在 TypeScript 中,this 和 super 是两个非常重要的,它们在面向对象编程中起着至关重要的作用。this 指的是当前对象,super 指的是父类。

this

this 关键字用于引用当前对象。它可以在任何地方使用,包括方法、构造函数和属性。在方法中,this 指的是调用该方法的对象。在构造函数中,this 指的是正在创建的对象。在属性中,this 指的是包含该属性的对象。

例如,以下代码演示了如何使用 this

class Person {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const person = new Person('John Doe');
person.greet(); // Output: Hello, my name is John Doe

super

super 关键字用于调用父类的方法或属性。它只能在子类中使用。在子类的方法中,super 可以用来调用父类的方法或属性。在子类的构造函数中,super 可以用来调用父类的构造函数。

例如,以下代码演示了如何使用 super 关键字:

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  speak() {
    console.log(`I am an animal. My name is ${this.name}`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name); // Call the parent class's constructor
  }

  bark() {
    console.log(`Woof! I am a dog. My name is ${this.name}`);
  }
}

const dog = new Dog('Spot');
dog.speak(); // Output: I am an animal. My name is Spot
dog.bark(); // Output: Woof! I am a dog. My name is Spot

总结

this 和 super 是 TypeScript 中非常重要的两个关键字,它们在面向对象编程中起着至关重要的作用。this 指的是当前对象,super 指的是父类。通过理解和掌握 this 和 super 的用法,可以更轻松地编写出高质量的 TypeScript 代码。