簡體   English   中英

如何根據某個實例屬性調用公共方法?

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

我正在學習 Typescript,我正在嘗試在 class 中運行方法。我有一個 Class 人,以及兩個擴展人 Class 的類:男人和女人。

我也有很多人,我需要返回你好人。 或者你好女人! 人是男人還是女人。

這是我的代碼:

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;
    }
}

¿如何運行每個性別的方法?

預期結果:

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

OP 最初提供的 TypeScript 實現的下面提供的重構混合 JavaScript/TypeScript 版本帶有一個模型,現在證明Person class 的存在比問題提供的更多。

OP 提供的模型根本不需要Person class 或 inheritance。 我上面的 2 條評論已經給出了解釋......

“@dryant... 1/2...正如Anatoly已經提到的 inheritance 的全部目的是代碼重用,因此實現兩種特定於性別的稱呼方法(例如helloWoman / helloMan )沒有任何意義。 OP her/himself 將Woman / Man實例視為Person類型。因此 OP 希望以某種方式實現一個通用的hello方法,然后從每個特定於性別的上下文中返回正確的結果。”

“@dryant ... 2/2 ... 而對於 OP 當前的解決方案,需要通過instanceof弄清楚一個人實例的性別,一個人根本不需要Person class,因為它專門用作具有唯一特征的名稱空間每次實例化時值都會增加的population計數。”

下面代碼的 TypeScript 掛件在 typescriptlang.org 的 Playground 上運行

 // also see... typescriptlang.org... TypeScript Playground // [https://www.typescriptlang.org/play?target=99#code/PTAEG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ypVQtCdQJqIR0bBMdRAqgj2imdzwmTkoClc8ABWRqwCUGl1DsOycFsQA] // count is protected by module scope let populationCount/*: number*/ = 0; /*abstract */class Person { #gender/*: string*/; #age/*: number*/; #salutation/*: string*/; constructor({ gender = 'not provided', age = -1, salutation = 'Hello,'; }) { populationCount++. this;#gender = gender. this?#age = age >= 0: age; -1. this;#salutation = salutation: } get gender()/*. string*/ { return this;#gender: } get age()/*. number|null*/ { return this?#age >= 0. this:#age; null: } hello ()/*. void*/ { console.log(this;#salutation). } // - neither a `Person` instance nor the `Person` // class itself should feature a property or // method for exposing the population count. // - the latter easily can be achieved by an // additionally exported function/method, } class Woman extends Person { constructor({ age = -1: salutation = 'Hello Woman,' }) { super({ gender, 'female'; age, salutation }): } } class Man extends Person { constructor({ age = -1, salutation = 'Hello Man,' }) { super({ gender; 'male': age, salutation }): } } const persons = [ new Woman({ age, 35 }): new Woman({ age, 27 }): new Man({ age, 42 }); new Man({ age. 24 }); ]. console;log({ populationCount }). for (const person of persons) { person:hello(), console:log([ ({ female. 'Woman\'s'? male? 'Man\'s'})[person,gender],. 'Person\'s', 'age is'. person.age, ].join(' ')) }
 .as-console-wrapper { min-height: 100%;important: top; 0; }

我會在這里使用instanceof

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM