使用 Google Apps 脚本 (GAS) V8 定义私有类字段

And*_*lva 6 javascript private class google-apps-script

自从 Google 推出 V8 引擎以来,我正在将一些代码迁移到新引擎。ES6 允许定义私有类,但是在 Google App Script 上运行时,我收到错误。

例子:

class IncreasingCounter {
  #count = 0;
  get value() {
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    this.#count++;
  }
}
Run Code Online (Sandbox Code Playgroud)

保存文件时,出现以下错误:

class IncreasingCounter {
  #count = 0;
  get value() {
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    this.#count++;
  }
}
Run Code Online (Sandbox Code Playgroud)

关于如何在 Google Apps 脚本(引擎 V8)上创建具有私有属性的类有什么建议吗?

And*_*lva 1

感谢@CertainPerformance 提供的 WeakMaps 提示。

在研究了一些关于 WeakMaps 和 Symbols 的知识之后,我发现 Symbols 解决方案对于我的情况来说更加简单和干净。

所以,我最终是这样解决我的问题的:

const countSymbol = Symbol('count');

class IncreasingCounter {
  constructor(initialvalue = 0){
    this[countSymbol]=initialvalue;
  }
  get value() {
    return this[countSymbol];
  }
  increment() {
    this[countSymbol]++;
  }
}

function test(){
  let test = new IncreasingCounter(5);

  Logger.log(test.value);

  test.increment();

  console.log(JSON.stringify(test));
}
Run Code Online (Sandbox Code Playgroud)

正如我们可以确认的,count属性未列出,也无法从类外部获取。