In typescript, this
and super
is a keyword used in object-oriented programming to refer to the current instance of a class and a base class respectively.
definition: refers to the current instance of the category.
Use cases:
- Access instance properties and methods.
- Call another method in the same class.
- Pass the current object as a parameter
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();
- Definition: Refers to the base category (parent category) of the current category.
- Use cases:
- Call the constructor of the base class.
- Access methods and properties from base class
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();
The output includes: makeSound() for the base category is Animal and makeSound for the subcategory is Dog, as follows:
Buddy makes a sound.
Buddy barks.
1. this
:
- always refers to current instance
- Can be used with constructors, methods, or arrow functions.
- In the arrow function,
this
Be lexically bound to the surrounding context.
*2. super
: *
- Can only be used within a category that extends another category.
- Must be called in the constructor before accessing
this
In derived categories. - Methods that can be used to call parent classes.
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
Correct, you can effectively manage inheritance and object behavior in Typescript.