In Typescript, this and super are keywords used in object-oriented programming to refer to the current instance of a class and the base class, respectively.
Definition: Refers to the current instance of the class.
Use Case:
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();
Example:
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();
and the output include: makeSound() of Base Class is Animal and makeSound of subclass is Dog like this:
Buddy makes a sound. Buddy barks.
1. this:
*2. super: *
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!
By using this and super correctly, you can manage inheritance and object behavior effectively in Typescript.
The above is the detailed content of Understanding This and Super in Typescript. For more information, please follow other related articles on the PHP Chinese website!