电子表格脚本和脚本库之间的可变范围 [英] Variable scope between spreadsheet script and script library

查看:81
本文介绍了电子表格脚本和脚本库之间的可变范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可以用作库将脚本加载到所需的电子表格中.

I have a script that I use as a library loading it in the spreadsheets I need.

当我将其添加到电子表格时,我定义了一个onEdit和onLoad函数,它们正在调用该库的相应方法.

When I add it to a spreadsheet, I define an onEdit and onLoad function that are calling the library's corresponding methods.

我需要使用该库的各个工作表来定义应该对库可用的全局变量,该变量可能未在工作表的单元格中设置.

I need my individual sheets that are using the library, to define a global variable that should be available to the library, that variable may not be set in a sheet's cell.

我尝试设置

var previd = "myid";

在电子表格脚本的开头,但这似乎无法解决问题.

at the beginning of the spreadsheet script but that doesn't seem to do the trick.

我该如何解决?

推荐答案

脚本之间不共享全局作用域",它实际上是脚本作用域".

The "global scope" is not shared between scripts, it is actually a "script scope".

库函数所需的所有变量都必须作为参数传递给这些函数.如果使用相同的参数进行许多函数调用,则应考虑将它们包装在object中.

All variables needed for your library functions must be passed as parameters to these functions. If you make many functions call with the same parameters you should consider wrapping them in an object. Like some Apps Script built-in functions have optArguments.

您还可能在库上具有setParameters函数,以一次(在每个运行时)传递这些变量,并使它们可用于下一次库调用.像这样:

You may also have a setParameters function on your library to pass these variables once (per runtime) and have them available to next library calls. Something like this:

//on the library script
var clientParams = null;
function setParameters(parameters) { clientParams = parameters; }
function exampleFunc() { return clientParams.previd; }


//on your client script
library.setParameters({previd:'myid', otherParam:'example'});

//then you can call
library.exampleFunc();

这篇关于电子表格脚本和脚本库之间的可变范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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