使用getter和setter的优点是什么 - 只能获取和设置 - 而不是简单地使用公共字段来存储这些变量?
如果getter和setter做的不仅仅是简单的get/set,我可以非常快地解决这个问题,但我并不是100%清楚如何:
public String foo;
Run Code Online (Sandbox Code Playgroud)
更糟糕的是:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Run Code Online (Sandbox Code Playgroud)
而前者需要很少的样板代码.
我对ECMAScript 6类中getter和setter的重点感到困惑.什么目的?以下是我所指的一个例子:
class Employee {
constructor(name) {
this._name = name;
}
doWork() {
return `${this._name} is working`;
}
get name() {
return this._name.toUpperCase();
}
set name(newName){
if(newName){
this._name = newName;
}
}
}
Run Code Online (Sandbox Code Playgroud) 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);
Run Code Online (Sandbox Code Playgroud)
这是我的代码.我创建了一个getter和setter为_name成员.我没有创建一个getter和setterfor age.
但两者都可以像这样更新这两个字段 man.name = 'B';man.age = 20;
所以,我很困惑,是getter和setter必要在JavaScript?
我试图了解以下优点是什么(如果有的话):
const obj = {
forename: 'Foo',
surname: 'Bar',
get name() {
//yes I get that I can do other stuff here
return this.forename+' '+this.surname;
}
}
alert(obj.name); //Foo Bar
Run Code Online (Sandbox Code Playgroud)
...超过...
const obj = {
forename: 'Foo',
surname: 'Bar',
name() {
return this.forename+' '+this.surname;
}
}
alert(obj.name()); //Foo Bar
Run Code Online (Sandbox Code Playgroud)
我已经阅读了 ( 1 ; 2 ; 3 ) 但似乎看不到除了可读性和代码风格之外的任何好处。仅此而已吗?两种方法之间没有隐含的行为变化?
是否只关注 JavaScript 中未来的类属性/方法可见性?这是有道理的 - 私有财产的吸气剂。但是因为那还没有,我看不出上面的意思。
任何人都可以启发我吗?
getter ×2
javascript ×2
oop ×2
setter ×2
abstraction ×1
class ×1
ecmascript-5 ×1
ecmascript-6 ×1
java ×1