gpt4 book ai didi

typescript - Typescript 中的 Getter/Setter

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:36 24 4
gpt4 key购买 nike

我正在学习关于 Typescript 类的教程,教学人员创建了一个类和一些 setter/getter 方法。但是当我阅读 Typescript Documentation 时方法有些不同。谁能帮我理解这两种方法之间的区别。

方法一:

class Student {
private _name: string;

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

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

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

方法二:

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。谁能帮我理解这两种方法之间的区别。

最佳答案

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

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

方法一

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

方法二

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

关于typescript - Typescript 中的 Getter/Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51646513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com