我正在玩ES6 Class
,我想知道在该类的属性中使用get
或set
方法的重点是什么。它们似乎毫无意义b / c你可以设置任何类的任意属性。
例如使用此类
class Group {
constructor() {}
set name(newName) {
this._name = newName;
}
get name() {
return this._name;
}
print() {
console.log('this._name = ', this._name);
console.log('this.name = ', this.name);
}
}
我得到了这些结果
var group = new Group();
group._name = 'foo';
console.log('_name = ', group._name); => _name = foo
console.log('name = ', group.name); => name = foo
group.print(); => this._name = foo
=> this.name = foo
var group2 = new Group();
group2.name = 'bar';
console.log('_name = ', group2._name); => _name = bar
console.log('name = ', group2.name); => name = bar
group2.print(); => this._name = bar
=> this.name = bar
使用此示例的结果,似乎使用新的set
和get
方法只会给我的课程增加不必要的膨胀。
答案 0 :(得分:1)
使用属性访问器可以运行其他代码,例如,检查值是否有效:
set name(newName) {
if (newName === '')
throw new Error("Name cannot be empty");
this._name = newName;
}
或计算复杂属性:
get fullname() {
return this.firstName + ' ' + this.lastName;
}