Typescript-更好:获取/设置属性 [英] Typescript - What is better: Get / Set properties

查看:93
本文介绍了Typescript-更好:获取/设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近才发现有关将get和set关键字用于类属性的问题,我想知道将get/set用于打字稿类时的首选方法是什么

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.

推荐答案

字母和二传手有多种用途,例如

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

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

这篇关于Typescript-更好:获取/设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆