Search code examples
javascripttypescriptclasses6-classsubclassing

How to invoke a public method depending on a certain instance property?


I'm learning Typescript and I'm trying to run method in a class. I have a Class Person, and two classes which extends the Person Class: Man and Woman.

I also have an array of persons, and I need returns hello man! or hello woman! if person is a man or if is a woman.

This is my code:

abstract class Person {
    static population: number = 0;
    constructor() {
        Person.population ++ ;
    }
}

class Man extends Person {
    age!: number;

    constructor(age: number) {
        super();
        this.age = age;
    }

    public helloMan() {
        console.log('Hello Man!');
    }
}

class Woman extends Person {
    age!: number;

    constructor(age: number) {
        super();
        this.age = age;
    }

    public helloWoman() {
        console.log('Hello Woman!');
    }
}

let persons: Person[] = [];
persons.push(new Man(24));
persons.push(new Woman(27));
persons.push(new Man(42));
persons.push(new Woman(35));

for(let person of persons){

    let typeOfPerson = Object.getPrototypeOf(person).constructor.name;
    switch (typeOfPerson) {
        case "Man":
            // run helloMan method
            break;
    
        case "Woman":
            // run helloWoman method
            break;
    
        default:
            break;
    }
}

¿How I can run the method of each gender?

expected result:

Hello Man!
Hello Woman!
Hello Man!
Hello Woman!

Solution

  • I would use instanceof here:

    if (person instanceof Man) {
        person.helloMan()
    } else if (person instanceof Woman) {
        person.helloWoman()
    }