angular - typescript - 什么是更好的 : Get/Set properties

标签 angular typescript oop

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

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

我只是好奇是否有任何最佳实践、性能或其他因素。

最佳答案

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

关于angular - typescript - 什么是更好的 : Get/Set properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49053103/

相关文章:

angular - 通用类型 'ComponentRef<C>' 需要 1 个类型参数

node.js - Angular 通用代理

c# - 如何使用 Entity Framework Core 可视化设计我的数据库?

java - UML 类图资源

c++ - 组合:使用特征来避免转发功能?

javascript - Mat-table 性能问题 - 一旦表格加载,它会卡住页面

html - 从迭代循环中隐藏特定内容并在隐藏面板中显示

javascript - 如何在 React Native 中管理用户 session ?

带有可选参数的 TypeScript lambda 函数

java - 在 Java 中全局访问命令行参数的最佳实践