来自 class get 方法的 return 值是否被垃圾收集?

Are the return values from class get methods garbage collected?

假设我有一个 class 方法 calculatePrice returns 一个值。它还有另一种使用 calculatePrice:

的方法
class SodaCan {

  constructor(id, otherArgs) { 
    this.id = id
    // more constructor logic
  }

  calculatePrice() {
    // do some calculations for tax, recycling, whatever
    return price;
  }

  savePriceToDb() {
    const price = this.calculatePrice();
    database.save(this.id, { price });
  }

}

// in the global scope:
const coke = window.coke = new SodaCan('someId', 1.19)
coke.savePriceToDb();

一旦 savePriceToDb 完成执行,就不再有对 price 的引用,所以我的假设是 price 被垃圾收集。但是,coke.id 不会被垃圾回收,因为它是 coke 的 属性,在全局范围内可用。如果这不正确,请告诉我!

现在假设我们将 calculatePrice 更改为 get 方法,比如 get price:

class SodaCan {

  constructor(id, otherArgs) { 
    this.id = id
    // more constructor logic
  }

  get price() {
    // do some calculations for tax, recycling, whatever
    return price;
  }

  savePriceToDb() {
    const price = this.price;
    database.save(this.id, { price });
  }

}

// in the global scope:
const coke = window.coke = new SodaCan('someId', 1.19)
coke.savePriceToDb();

(假设 savePriceToDb 函数真的不需要说 const price = this.price,因为它可以调用 database.save(this.id, { price: this.price })

使用 get 语法,this.price 的结果附加到实例。由于 coke 在全局范围内可用,因此 coke.price 仍会引用它,并且 不会 被垃圾收集。对吗?

如果我的假设是正确的,就内存管理而言,这是在 class 上使用 get 方法的缺点吗?如果我不理解这里的某些内容,或者我的假设不正确,请告诉我。

With the get syntax, the result of this.price is attached to the instance.

不,不是。 getter 只是让它看起来像是一个 属性,但事实并非如此。每次读取 this.price 时,它都会调用 getter 函数和 returns 值,就像 calculatePrice() 方法一样。该值未附加到任何地方。

所以如果调用者不在任何地方保存价格,它就会变成垃圾。