javascript - 函数按值返回函数

标签 javascript function reference google-sheets

我正在尝试根据某些标准使用 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。我相信这是由于 sssht 通过引用而不是通过值传递。有什么办法可以解决这个问题吗?

最佳答案

这里还有一种将 sht 绑定(bind)到闭包的方法:

scope[funcName] = function(_sht) {
  return function() {
    ss.setActiveSheet(_sht);
  }
}(sht);

(参见这个问题,它很相似:javascript closure immediate evaluation)

关于javascript - 函数按值返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45247934/

相关文章:

java - 如何在 Java XML 中使用引用 URI 加载外部资源

javascript - 在 MVC 中有条件地更改字体颜色

javascript - ( Node :9263) UnhandledPromiseRejectionWarning: ValidationError: ideas validation failed: imageUrl: Path `imageUrl` is required

c++ - 参数传递

bash - 如何记录shell函数?

c++ - libc++ 中的 std::min 没有悬挂引用

c# - 对同一对象的两个引用的不同属性值 (C#)

javascript - jQuery 函数问题(父/子)

javascript - knockout JS : foreach that increments by 2

c - 我想知道为什么一个函数在从 x 调用时执行得很好,但在从 y 调用时却执行得不好