getter 函数何时在 JavaScript 中有用?

When is a getter function useful in JavaScript?

特别是在对象内使用时,什么时候 getter 函数会在常规函数上使用。比如using

有什么区别
const obj = {
        get method() {
                return data;
        }
};
console.log(obj.method);

还有这个

conts obj = {
        method() {
                return data;
        }
};
console.log(obj.method());

一个方法只能return个数据属性也可以有一个setter

如果您想公开 read-only 属性,这很有用。它不仅仅是调用者的函数。

在你的例子中,两者做同样的事情,但重要的不是它们有多相似,而是它们有多不相似。例如,您可以将方法版本作为参数传递到其他地方以执行一些延迟执行,但 getter 不会那样工作。

const obj = {
  lazyProp(parameter) {
    return parameter + 2;
  }
}

function evaluateLazy(fn) {
  return fn()
}

evaluateLazy(obj.lazyProp)

1。对于正常 property/method,您可以 更改其值 。 getter 方法不能更改其值。看看当我们尝试在此处更改 getter 时会发生什么(它不会更改):

const obj = {
    methodNormal() {
        return 5;
    },
    get methodGetter() {
        return 5;
    }
};

obj.methodNormal = "red";
obj.methodGetter = "blue";

console.log(obj);

2。其次,对于正常的 属性,您可以选择返回函数 obj.methodNormal 或返回函数 executingobj.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 具有 'hiddenness' 意义的函数。现在您可以理解人们说 getter 是 'read-only' 属性的意思了!


进一步阅读:
我一直提到的 'normal properties' 称为数据属性 (good article).
Getter 方法是所谓的访问器属性 (good article) 的示例。

一个有用的场景是您希望对所有属性使用常规 属性 访问,但需要调用一个方法来计算给定值。例如,以不使用 getter 的以下示例为例。它最终打印函数,而不是函数的 return 值。如果没有 getter,我们将需要处理值为函数的特定情况,然后调用它。

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);

但是,对于 getter,我们可以使用相同的函数,并且不需要处理 obj[key] 是函数的特定情况,只需执行 obj[key]在 getter 上将为您调用函数:

const obj = {
  x: 10,
  y: 20,
  get total() {
    return this.x + this.y;
  }
}

const prettyPrintObj = obj => {
  for(let key in obj) {
    console.log(`${key.toUpperCase()} is ${obj[key]}`);
  }
}

prettyPrintObj(obj);