gpt4 book ai didi

javascript - JavaScript getter 方法的意义何在?

转载 作者:行者123 更新时间:2023-12-04 23:35:19 25 4
gpt4 key购买 nike

我试图了解以下优势(如果有的话):

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 中 future 的类属性/方法可见性?这是有道理的——私有(private)属性(property)的 setter/getter 。但由于那还不在这里,我看不出上面的意思。

任何人都可以启发我吗?

最佳答案

一个区别是 typeof 在使用 getter 时实际上会按预期工作,也就是说,它将返回 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');

但我们也可以争辩说后者在某些情况下可能更合适。

关于javascript - JavaScript getter 方法的意义何在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59569178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com