打字稿中的获取/设置者

时间:2018-08-02 06:02:52

标签: typescript

我正在跟踪有关Typescript类的教程,而教书的人创建了一个类以及一些setter / getter方法。但是当我读Typescript Documentation时,方法有所不同。有人可以帮助我了解这两种方法之间的区别。

方法1:

class Student {
private _name: string;

constructor(name:string) {
    this._name=name;
}

getName = (): string => {
    return this._name;
}

setName = (name: string) => {
    this._name = name;
}
}

方法2:

class Student {
private _name: string;

constructor(name:string) {
    this._name=name;
}

public get name(): string {
    return this._name;
}


public set name(value: string) {
    this._name = value;
}
}

看看。在方法1中,我们将getter / setter编写为常规函数,但在方法2中,使用了关键字get / set。有人可以帮助我了解这两种方法之间的区别。

1 个答案:

答案 0 :(得分:7)

使用它们的方式不同。在第一种情况下,您需要明确调用get/set方法。在第二秒中,您可以像在类上的实际字段一样使用name,运行时将自动调用get/set访问器。

考虑将字符附加到名称的简单示例:

方法1

let s = new Student();
s.setName(s.getName() + "A") // we need to explicitly call the get/ set methods

方法2

let s = new Student();
s.name += "A" // we can use += and the get/set accessors will get called for us

在幕后,get/set访问器方法(方法2)将使用Object.defineProperty