javascript - JavaScript getter 方法的意义何在?
问题描述
我试图了解以下优势(如果有的话):
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
...超过...
const obj = {
forename: 'Foo',
surname: 'Bar',
name() {
return this.forename+' '+this.surname;
}
}
alert(obj.name()); //Foo Bar
我已经阅读了(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);
当然,您可以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);
无论如何,我认为 getter 和 setter 的最大优势之一就是增加了可读性并减少了冗长,尽管这通常归结为个人喜好。无论如何,我宁愿使用:
person.name = 'Alice Smith';
比:
person.setName('Alice', 'Smith');
但我们也可以争辩说后者在某些情况下可能更合适。
推荐阅读
- apache - Apache Perl CGI 脚本 sso 麻烦和环境变量
- python - Python UnicodeDecodeError - 如何从子进程中正确读取 unicode 字符串?
- php - 提交表单后什么都没有发生
- javascript - 奇怪的 JQuery location.reload() 行为?
- python-3.x - Python Pandas:根据第一列的内容对 CSV 文件进行排序
- android - Editable 对象与 EditText 文本属性之间的关系
- sql - 表值函数输出参数列表
- angular - Angular:带参数的自定义验证
- c# - 删除对 datagridview 数据源更改的控制
- dart - 扑扑为什么会被解雇两次?