Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Google Apps脚本(GAS)V8定义私有类字段_Javascript_Google Apps Script - Fatal编程技术网

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

Javascript 使用Google Apps脚本(GAS)V8定义私有类字段,javascript,google-apps-script,Javascript,Google Apps Script,自从Google推出V8引擎以来,我正在将一些代码迁移到新引擎。 ES6允许定义私有类,但当在Google应用程序脚本上运行时,我遇到了一个错误 例如: class IncreasingCounter { #count = 0; get value() { console.log('Getting the current value!'); return this.#count; } increment() { this.#count++; } }

自从Google推出V8引擎以来,我正在将一些代码迁移到新引擎。 ES6允许定义私有类,但当在Google应用程序脚本上运行时,我遇到了一个错误

例如:

class IncreasingCounter {
  #count = 0;
  get value() {
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    this.#count++;
  }
}
保存文件时,出现以下错误:

Error: Line 2: Unexpected token ILLEGAL (line 5075, file "esprima.browser.js-bundle.js")

关于如何在Google Apps脚本(engine V8)上创建具有私有属性的类的任何建议?

感谢@CertainPerformance提供的WeakMaps提示

在研究了一些弱贴图和符号之后,我发现符号解决方案对于我的案例来说更简单、更清晰

因此,我最终像这样解决了我的问题:

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

正如我们所确认的,count属性未列出,也不可从类外部使用。

类字段为。GAS使用的V8版本不能像Chrome那样是最新的。一旦情况完全稳定,他们可能会在几个月内更新它。如果你想的话,你可以先用一个transpiler。您还可以使用WeakMap
console.log(Object.getOwnPropertySymbols(test)[0])手动执行此操作//预期输出符号(计数)