问题描述
特别是在对象内使用时,何时在常规函数上使用getter函数。例如,使用
有什么区别const obj = {
get method() {
return data;
}
};
console.log(obj.method);
还有这个
conts obj = {
method() {
return data;
}
};
console.log(obj.method());
解决方法
1。使用常规的属性/方法,您可以更改其值。 getter方法的值不能更改。看看当我们尝试在此处更改吸气剂时(不会改变)会发生什么:
const obj = {
methodNormal() {
return 5;
},get methodGetter() {
return 5;
}
};
obj.methodNormal = "red";
obj.methodGetter = "blue";
console.log(obj);
2。其次,通过普通属性,您可以奢侈地返回函数obj.methodNormal
或返回函数 execute (即obj.methodNormal()
)。使用getter函数,您将无法获得返回函数的奢侈体验。您只能执行执行该功能的obj.methodGetter
。下面的代码段演示了这一点。
const obj = {
methodNormal() {
return 5;
},get methodGetter() {
return 5;
}
};
let captureNormalMethod = obj.methodNormal;
let captureGetterMethod = obj.methodGetter;
console.log(captureNormalMethod);
console.log(captureGetterMethod);
这两种特性-不可更改且无法在新变量或属性中捕获-有助于具有“隐藏”感的吸气剂功能。现在您可以理解人们说吸气剂是“只读”属性的意思!
进一步阅读:
我一直所说的“常规属性”称为数据属性(good article)。
吸气剂方法是所谓的访问器属性(good article)的示例。
一个方法只能返回数据,一个属性也可以有一个setter
,如果要公开只读属性,这很有用。不仅仅是调用者的功能。
,在您的示例中,两者都做同样的事情,但是重要性不是彼此的相似之处,而是彼此之间的相似之处。例如,您可以将方法版本作为参数传递给其他地方,以进行一些延迟执行,但是getter不能那样工作。
const obj = {
lazyProp(parameter) {
return parameter + 2;
}
}
function evaluateLazy(fn) {
return fn()
}
evaluateLazy(obj.lazyProp)
,
一个有用的方案是您要对所有属性使用常规属性访问,但需要调用一种方法来计算给定值。例如,下面的示例不使用吸气剂。最终打印函数,而不是函数的返回值。没有吸气剂,我们将需要处理一个特定的情况,即值是一个函数,然后调用它。
const obj = {
x: 10,y: 20,total() {
return this.x + this.y;
}
}
const prettyPrintObj = obj => {
for(let key in obj) {
console.log(`${key.toUpperCase()} is ${obj[key]}`);
}
}
prettyPrintObj(obj);
但是,使用吸气剂,我们可以使用相同的函数,并且不需要处理obj[key]
是函数的特定情况,因为只需在吸气剂上执行obj[key]
即可调用为您服务:
const obj = {
x: 10,get total() {
return this.x + this.y;
}
}
const prettyPrintObj = obj => {
for(let key in obj) {
console.log(`${key.toUpperCase()} is ${obj[key]}`);
}
}
prettyPrintObj(obj);