如何在Google Apps脚本中定义全局变量 [英] How to define global variable in Google Apps Script

查看:202
本文介绍了如何在Google Apps脚本中定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到Google的大多数例子都是在一个巨大的脚本中使用唯一的功能。

例如。 https://developers.google.com/apps-script/quickstart/macros



但是在我们的风格中,我们通常在一个名称空间下编写所有的函数,比如

  MyCompany =(MyCompany || {}); 
MyCompany.init = function(){
Logger.log('init');
};

函数onOpen(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menus = [{
name:Init,
functionName:MyCompany.init
}];
spreadsheet.addMenu(测试,菜单);
};

然而,当我运行上面的代码时,它会返回

 我的公司未定义。 

如何解决?

解决方案

使用Properties Service可能会更好,因为您可以将它们用作一种持久的全局变量。

单击'file>项目属性>项目属性'来设置一个键值,或者您可以使用

  PropertiesService.getScriptProperties()。setProperty('mykey' ,'myvalue'); 

数据可以通过

var myvalue = PropertiesService.getScriptProperties()。getProperty('mykey');


I see most examples from Google is they use only functions in a single giant script.

e.g. 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."

How to solve?

解决方案

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

The data can be retrieved with

var myvalue = PropertiesService.getScriptProperties().getProperty('mykey');

这篇关于如何在Google Apps脚本中定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆