Utk*_*nos 5 javascript oop getter-setter ecmascript-5
我试图了解以下优点是什么(如果有的话):
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 时实际上会按预期typeof工作,也就是说,它将返回 getter 返回的原语的实际类型,而使用方法将始终返回:function
const objGetter = {
forename: 'Foo',
surname: 'Bar',
get name() {
return `${ this.forename } ${ this.surname }`;
}
}
const objGetterLogic = {
forename: undefined,
surname: 'Bar',
get name() {
return this.forename ? this.surname : 3;
}
}
const objMethod = {
forename: 'Foo',
surname: 'Bar',
name() {
return `${ this.forename } ${ this.surname }`;
}
}
console.log(`objGetter`, typeof objGetter.name);
console.log(`objMethod`, typeof objMethod.name);
console.log(`objGetterLogic (without forename)`, typeof objGetterLogic.name);
objGetterLogic.forename = 'Alice';
console.log(`objGetterLogic (with forename)`, typeof objGetterLogic.name);Run Code Online (Sandbox Code Playgroud)
当然,您可以使用name()该方法调用该版本,但使用将透明地工作的 getter。
另外,如果您有嵌套的 getter,则可以透明地调用它们,如果您以编程方式导航对象,这会派上用场,否则,您需要考虑属性是值或需要的属性的function可能性被调用以获取您需要的实际值:
class Shape {
constructor(type, children) {
this.type = type || '';
this.children = children || [];
}
get firstChild() {
return this.children[0];
}
get lastChild() {
return this.children[this.children.length - 1];
}
}
const group1 = new Shape('group1', [
new Shape('a'),
new Shape('b'),
new Shape('c'),
]);
const group2 = new Shape('group2', [
new Shape('d'),
new Shape('e'),
new Shape('f'),
]);
const group4 = new Shape('group4', [
group1,
group2,
]);
console.log(group4.firstChild.lastChild.type);Run Code Online (Sandbox Code Playgroud)
无论如何,我认为 getter 和 setter 的最大优点之一就是增加可读性并减少冗长,尽管这通常取决于个人喜好。无论如何,我宁愿使用:
person.name = 'Alice Smith';
Run Code Online (Sandbox Code Playgroud)
比:
person.setName('Alice', 'Smith');
Run Code Online (Sandbox Code Playgroud)
但我们也可以认为后者在某些情况下可能更合适。
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |