如何在 Google Apps Script 中定义全局变量 [英] How to define global variable in Google Apps Script
本文介绍了如何在 Google Apps Script 中定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到来自谷歌的大多数例子是他们只在一个巨大的脚本中使用函数.
I see most examples from Google is they use only functions in a single giant script.
例如https://developers.google.com/apps-script/quickstart/macros
但在我们的风格中,我们通常将所有函数都写在一个命名空间下,比如
But in our style, we usually write all functions under a single namespace, such as
MyCompany = (MyCompany || {});
MyCompany.init = function () {
Logger.log('init');
};
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menus = [{
name: "Init",
functionName: MyCompany.init
}];
spreadsheet.addMenu("Test", menus);
};
然而,当我运行上面的代码时,它返回
However, when I run the code above, it return
"MyCompany is not defined."
如何解决?
推荐答案
您最好使用 Properties Service,因为您可以将它们用作一种持久性全局变量.
You might be better off using the Properties Service as you can use these as a kind of persistent global variable.
点击文件">项目属性 >项目属性'来设置一个键值,或者你可以使用
click 'file > project properties > project properties' to set a key value, or you can use
PropertiesService.getScriptProperties().setProperty('mykey', 'myvalue');
可以用
var myvalue = PropertiesService.getScriptProperties().getProperty('mykey');
这篇关于如何在 Google Apps Script 中定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文