JavaScript中是否需要`getter`和`setter`? [英] Are `getter` and `setter` necessary in JavaScript?
问题描述
class Employee {
constructor(name, age) {
this._name = name;
this.age = age;
}
doWork() {
return `${this._name} is working`;
}
get name() {
return this._name.toUpperCase();
}
set name(newName){
if(newName){
this._name = newName;
}
}
}
let man = new Employee('A', 10);
console.log(man.name, man.age);
man.name = 'B';
man.age = 20;
console.log(man.name, man.age);
这是我的代码.我为 _name
成员创建了一个 getter
和 setter
.我没有为 age
创建一个 getter
和 setter
.
Here is my code. I created a getter
and setter
for _name
member. I did not create a getter
and setter
for age
.
但是两者都可以更新这两个字段,例如 man.name ='B'; man.age = 20;
But both can update these two fields like this man.name = 'B';man.age = 20;
所以我很困惑,JavaScript中是否需要 getter
和 setter
?
So I am confused, are getter
and setter
necessary in JavaScript?
推荐答案
是的,有时 getter
或 setter
可能非常有用,但它们只需要在需要其特定功能时使用-否则,无简单地进行属性访问就可以了.
Yes, a getter
or setter
can be very useful at times, but they only need to be used when their specific functionality is required - otherwise plain property access without a getter
or setter
can be just fine.
每次要请求属性时都想运行一些代码时,可以使用 getter
.在您的示例中, getter
始终返回名称的大写版本,而不管名称的大小写如何,同时保留实际的大小写以供内部使用.
A getter
has use when you want to run some code every time a property is requested. In your example, the getter
always returns an uppercase version of the name regardless of what the case of the name is, while reserving the actual case for internal use.
在每次设置属性时都想运行一些代码时,可以使用 setter
.在您的情况下,它可以防止设置假名称.没有 getter
/ setter
,您将无法实现这两个功能.
A setter
has use when you want to run some code every time a property is set. In your case, it prevents the setting of a falsey name. You can't implement either of those features without a getter
/setter
.
直接属性访问是在不需要 getter
或 setter
特殊逻辑的情况下做事的完美方法.
Direct property access is a perfectly fine way to do things when you don't need getter
or setter
special logic.
getters
和 setters
也可能会获得并设置一些不公开的属性(因此通过常规属性访问根本不可用),原因可能是它存储在不同的地方(不是作为此对象的属性),也可以私下存储,甚至可以存储在其他地方,例如某些硬件设备中.在这些情况下, getter
和 setter
会模拟实际上不在属性中的值.因此,它们简化了界面,同时允许在任何地方存储或检索实际值.
It's also possible that getters
and setters
may get and set some property that is not publicly available (so not available at all via a normal property access), either because it's stored somewhere differently (not as a property on this object) or stored privately or even that it's stored else such as in some hardware device. In these cases, the getter
and setter
simulate the value being in a property when it actually isn't. So, they simplify the interface while allowing the actual value to be stored or retrieved from anywhere.
这篇关于JavaScript中是否需要`getter`和`setter`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!