请参阅下面的示例,
function doSomething1(){/*needs ss*/const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);}
function doSomething2(){/*needs ss*/const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);}
function doItAll(){
doSomething1();
doSomething2();
}
可以使用全局变量来简化,而不是在两个函数中调用 Spreadsheet
const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);
function doSomething1(){/*do something with ss*/}
function doSomething2(){/*do something with ss*/}
function doItAll(){
doSomething1();
doSomething2();
}
这里的问题可以在不使用全局变量的情况下通过简单地传递来解决ss
函数之间的变量。但这会变得更加复杂,因为多个功能需要访问ss
多变的。并且路过ss
很麻烦。没有太多方法可以避免应用程序脚本中的全局。不支持模块。如果您使用 IIFE,则所有函数都对 IDE 隐藏,从而无法从 IDE 或其他任何地方调用函数。在这里使用全局要优雅得多。但如果我有一个简单的触发器,就会出现问题:
const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);
function doSomething1(){/*do something with ss*/}
function doSomething2(){/*do something with ss*/}
function doItAll(){
doSomething1();
doSomething2();
}
function onOpen(){/*Adds a menu*/}
菜单添加onOpen
将失败,因为该行已加载SpreadsheetApp.openById(/*SPREADSHEET_ID*/)
before onOpen
此行需要权限/授权,同时onOpen
作为一个简单的触发器,不运行任何需要授权的代码。
如何声明全局变量而不遇到授权错误?
这个问题可以通过使用来解决getter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get。 getter 仅在从任何地方调用时才执行代码,从而将代码的执行封装在全局上下文中。但是 getter 将在每次调用变量时执行。如果ss
在两个函数中被调用,SpreadsheetApp.openById
被执行两次。我们可以使用以下方法来避免这种情况延迟加载技术 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#ExamplesMDN 中提到过。
const config = {
get ss() {
delete this.ss;
return (this.ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/));
},
};
function doSomething1(){/*do something with config.ss*/}
function doSomething2(){/*do something with config.ss*/}
function doItAll(){
doSomething1();
doSomething2();
}
function onOpen(){/*Adds a menu*/}
在这里,我们使用一个getter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get在对象内部而不是直接声明ss
。用这种方式,SpreadsheetApp.openById()
尽管它是在全局范围内声明的,但从未在全局范围内调用。它仅在加载时doSomething1
被执行。此外,当从以下位置访问该方法时,不会再次调用该方法doSomething2
,因为 getter 在第一次访问时被删除并替换为实际值。
虽然代码变得有点庞大,但是这样解决了很多问题,而且优雅多了。
Samples:
-
避免重复:是否在 Google Apps 脚本中使用全局变量? https://stackoverflow.com/questions/70056310/avoid-repeating-use-global-variables-in-google-apps-script-or-not/70074204#70074204
-
使用延迟加载技术动态添加工作表和范围值等对象 https://stackoverflow.com/a/65134054/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)