理解 Typescript 中的 This 和 Super

在 Typescript 中,“this” 和 “super” 是面向对象编程中使用的关键字,分别指代类的当前实例和基类。

此关键字

**定义**:指类的当前实例。

**用例**:

  • 访问实例属性和方法。
  • 调用同一个类中的另一个方法。
  • 将当前对象作为参数传递
  • class Pizza {
        name: string
    
        constructor(name: string){
            this.name = name;
        }
    
        cook():void{
            console.log(`Start cooking ${this.name} pizza`)
        }
    }
    
    const pepperoniPizza = new Pizza("pepperoni");
    pepperoniPizza.cook();

    超级关键字

  • 定义:指当前类的基类(父类)。
  • 用例:调用基类的构造函数。访问基类的方法和属性
  • 例子:

    class Animal {
        name: string;
    
        constructor(name: string) {
          this.name = name;
        }
    
        makeSound(): void {
          console.log(`${this.name} makes a sound.`);
        }
      }
    
      class Dog extends Animal {
        constructor(name: string) {
          super(name); // Calls the constructor of the base class
        }
    
        makeSound(): void {
          super.makeSound(); // Calls the base class method
          console.log(`${this.name} barks.`);
        }
      }
    
      const dog = new Dog("Buddy");
      dog.makeSound();

    并且输出包括:基类的 makeSound() 是 Animal 并且子类的 makeSound() 是 Dog 像这样:

    Buddy makes a sound.
    Buddy barks.
    Image description

    要点:

    **1. 这个:**

  • 始终引用当前实例
  • 可以在构造函数、方法或箭头函数中使用。
  • 在箭头函数中,this 在词汇上与周围的上下文绑定。
  • **2. 超级:**

  • 只能在扩展另一个类的类中使用。
  • 在派生类中访问此方法之前必须在构造函数中调用它。
  • 可用于调用父类方法。
  • class Parent {
      protected message: string = "Hello from Parent!";
    }
    
    class Child extends Parent {
      showMessage(): void {
        console.log(super.message); // Accesses the parent class property
      }
    }
    
    const child = new Child();
    child.showMessage(); // Output: Hello from Parent!

    通过正确使用“this”和“super”,你可以在Typescript中有效地管理继承和对象行为。