我正在尝试根据某些标准使用 Google 脚本 (JavaScript) 添加指向 Google 表格中菜单的链接。 Google's API template添加菜单项的方法如下:
addItem(caption, functionName)
functionName
参数本身不能接受输入参数,并且由于我的文档中的工作表数量可变,因此我尝试在 for 循环中生成任意数量的函数,以便它们无需任何输入参数即可使用:
function createGotoMenuFunctions(scope) {
var ss = SpreadsheetApp.getActive();
var sheets = ss.getSheets();
for (var s=0; s<sheets.length; s++){
var sht = sheets[s];
var shtName = sht.getName();
var funcName = 'goto' + shtName.replace(/\s/g, '_') + 'menu';
scope[funcName] = function() {
ss.setActiveSheet(sht);
}
}
}
createGotoMenuFunctions(this); //global scope
这将为每个工作表创建一组名为(例如)gotoSheet1menu()
、gotoSheet2menu()
、gotoSheet3menu()
的函数。但是,当我调用任何函数时,它们都会激活最后一张纸。例如,如果我调用 gotoSheet1menu()
,它会激活 Sheet3。我相信这是由于 ss
和 sht
通过引用而不是通过值传递。有什么办法可以解决这个问题吗?
最佳答案
这里还有一种将 sht
绑定(bind)到闭包的方法:
scope[funcName] = function(_sht) {
return function() {
ss.setActiveSheet(_sht);
}
}(sht);
(参见这个问题,它很相似:javascript closure immediate evaluation)
关于javascript - 函数按值返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45247934/