自从 Google 推出 V8 引擎以来,我正在将一些代码迁移到新引擎。
ES6 允许定义私有类,但是在 Google App Script 上运行时,我收到错误。
Example:
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 脚本(引擎 V8)上创建具有私有属性的类有什么建议吗?
感谢@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));
}
正如我们可以确认的,count属性未列出,也无法从班级外部获得。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)