理解 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.

要点:
**1. 这个:**
**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中有效地管理继承和对象行为。