打字稿 - 什么是更好的:获取/设置属性

问题描述 投票:4回答:1

刚刚发现关于为类属性使用get和set关键字我想知道在使用get / set for typescript类时首选的方法是什么:

class example {
    private a: any;
    private b: any;

    getA(): any{
        return this.a;
    }

    setA(value: any){
        this.a = value;
    }

    get b(): any{
        return this.b;
    }

    set b(value: any){
        this.b = value;
    }
}

如果有任何最佳实践,表现或其他因素,我只是好奇。

angular typescript oop
1个回答
9
投票

Getter和Setters有几种用途,比如

如果未指定setter,则可以将私有变量设置为只读

class example {
    private _a: any;

    get a(): any{
        return this._a;
    }
}

当变量发生变化时,您可以使用它们来执行自定义逻辑,这是事件发射器的替代品

class example {
    private _a: any;

    set a(value: any){
        this._a = value;

        // Let the world know, I have changed
        this.someMethod();
    }

    someMethod() {
        // Possibly a POST API call
    }
}

您可以使用它们来为输出添加别名

class Hero {
    private _health: any = 90;

    get health(): string {
        if(this._health >= 50) {
            return "I am doing great!";
        } else {
            return "I don't think, I'll last any longer";
        }
    }
}

setter可用于清洁分配

class Hero {
    private _a: number;

    set a(val: number) {
        this._a = val;
    }

    setA(val: number) {
        this._a = val;
    }

    constructor() {
        this.a = 30;    // Looks cleaner
        this.setA(50);  // Looks Shabby, Method's purpose is to perform a logic not handle just assignments
    }
}

最后,setter的最大优势是能够在分配之前检查变量的正确值

class Hero {
    private _age: number;

    set age(age: number) {
        if (age > 0 && age < 100) {
            this._age = age
        } else {
            throw SomeError; 
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.