为什么我不能在 onOpen
中使用对象实例?
我正在使用新的 V8 运行时试验 Google Apps 脚本。我编写了一些简单的代码,在 onOpen
函数中创建一个类的实例,并在单击菜单项时尝试将调用关联到该实例上的方法。
当我单击关联的菜单条目时,出现“未找到脚本函数”错误。但是,当我创建该类的全局实例或在另一个函数中创建本地实例时,它工作得很好。
我尝试记录本地实例或全局实例的值,但它只显示一个空对象:{}
。
这是一个错误,还是我在阅读文档时错过的一些细节?
/** Application Class */
class Application {
/**
* ShowUi
*/
showUi() {
// const html = HtmlService.createHtmlOutputFromFile('Ui');
const html = HtmlService.createHtmlOutput('<h1>Hello World</h1>');
const ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, 'User Interface');
}
}
const global_app = new Application();
/** onOpen */
function onOpen() {
const app = new Application();
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('JSClass Example');
console.log('app, local scope:');
console.log(app);
console.log('app, global scope');
console.log(global_app);
menu.addItem('Show UI (local)', 'app.showUi');
menu.addItem('Show UI (global)', 'global_app.showUi');
menu.addItem('Show UI (global fn)', 'showUi');
menu.addToUi();
}
/** showUi */
function showUi() {
const app3 = new Application();
app3.showUi();
}
此代码的绑定(bind)电子表格是 here 。不过,我认为您必须制作一份副本并单击一些看起来吓人的警告才能实际运行它。
最佳答案
在您的示例中,onOpen()
方法仅在填充菜单时执行,但在选择菜单选项时不执行。
当您选择一个菜单项时,它将在新的执行上下文和 onOpen()
内的状态中执行。先前执行的功能(即填充菜单)不会被继承。
另一种方法是使用 static method ,您可以调用它而无需创建该类的实例。
class Application {
static showUi() {
const html = HtmlService.createHtmlOutput('<h1>Hello World</h1>');
const ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, 'User Interface');
}
}
function onOpen() {
const app = new Application();
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('V8 Menu Test');
menu.addItem('Show UI', 'Application.showUi');
menu.addToUi();
}
关于javascript - Google Apps 脚本 (V8);为什么我不能在 onOpen 内部使用对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218503/