Typescript - What is better: Get / Set properties

一世执手 提交于 2021-02-07 06:26:01

问题


Just recently discovered about using get and set keywords for class properties I was wondering what is the preferred method when using get / set for typescript classes:

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

I am just curious if there are any best practices, performance, or other factors.


回答1:


Getter and Setters have several uses, like

You can make a private variable read only, if you don't specify a setter

class example {
    private _a: any;

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

You can use them to execute a custom logic when a variable changes, sort of a replacement for Event Emitter

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

You can use them to alias an output

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

A setter can be used for a clean assignment

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

Finally setter's biggest strength is the ability to check variables for proper value before assignment

class Hero {
    private _age: number;

    set age(age: number) {
        if (age > 0 && age < 100) {
            this._age = age
        } else {
            throw SomeError; 
        }
    }
}


来源:https://stackoverflow.com/questions/49053103/typescript-what-is-better-get-set-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!