我用Google Apps Script制作的附加组件有很多变量,大约60个,可用于5种不同的功能。因此,这些变量在逻辑上必须是全局的。
但是60个变量中的20个需要ScriptApp.AuthMode
而不是NONE。我不想将它们复制粘贴到所有5个函数中,并希望保持它们有点全局,但是它们会导致脚本错误,而尚未授予授权。
在这种情况下,使这些变量可被函数访问而不是全局访问的最佳实践是什么?
正如亚当·H(Adam H)所指出的,这个问题非常广泛,因此我将更具体:
哪个最好?
答案 0 :(得分:1)
正确的方法应该是:
选项2:添加返回这些变量的函数
原因:
通过功能,您可以重用。而且将来如果某个变量的值需要更改,那么您只需要在一个位置进行更改。
我们不能选择选项3,因为它将不必要地一次又一次地添加相同的代码。
我们不能选择选项1并将变量保留为全局变量,因为这样一来就可以覆盖变量的值。
注意:
即使该函数可以用烤箱编写,也可以使用js闭包来保存变量,以免由于不希望的源或钩子而导致更新。
答案 1 :(得分:-1)
这是一个基于意见的主题,但这是我会做的,尽其所能。
// create your namespace
var myApp = (function() {
// variables that are local to your app
let myVariable;
// functions that are exposed by your app
return {
myFunction: function() {
// you can reference all the variables defined above here
return myVariable;
},
// your initialization function (or a poor mans constructor)
init: function(varValue) {
// store the values passed in here
myVariable = varValue;
}
};
})();
// Init your app with your variables
myApp.init('Random Value');
// Now you just call your functions
console.log(myApp.myFunction())