gpt4 book ai didi

javascript - 使用 Google Apps Scripts (GAS) V8 定义私有(private)类字段

转载 作者:行者123 更新时间:2023-12-04 10:14:41 24 4
gpt4 key购买 nike

由于 Google 推出了 V8 引擎,我正在将一些代码迁移到新引擎。
ES6 允许定义私有(private)类,但是在 Google App Script 上运行时,我遇到了错误。

例子:

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)上创建具有私有(private)属性的类的任何建议?

最佳答案

感谢@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 属性没有列出,也不能从类外部获得。

关于javascript - 使用 Google Apps Scripts (GAS) V8 定义私有(private)类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61132189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com