特别是当在对象内使用时,何时会使用 getter 函数而不是常规函数。例如,使用有什么区别
const obj = {
get method() {
return data;
}
};
console.log(obj.method);
还有这个
conts obj = {
method() {
return data;
}
};
console.log(obj.method());
最佳答案
1.使用普通属性/方法,您可以更改其值。 getter 方法不能更改其值。看看当我们尝试更改此处的 getter 时会发生什么(它没有更改):
const obj = {
methodNormal() {
return 5;
},
get methodGetter() {
return 5;
}
};
obj.methodNormal = "red";
obj.methodGetter = "blue";
console.log(obj);
2.其次,对于普通属性,您可以选择返回函数,即 obj.methodNormal
或返回正在执行的函数,即 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);
这两个特性 - 不可更改且无法在新变量或属性中捕获 - 都有助于 getter 函数具有“隐藏性”的感觉。现在您可以理解人们说 getter 是“只读”属性时的意思了!
进一步阅读:
我所说的“正常属性”称为数据属性( good article )。
Getter 方法是所谓的访问器属性 ( good article ) 的一个示例。
关于javascript - JavaScript 中 getter 函数什么时候有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63515708/