Is JavaScript function.bind() supported in google sheets?

余生颓废 提交于 2021-02-11 08:04:33

问题


Here a simple code i'm trying to run in google sheets script. The purpose is supplying the foreach callback function additional parameters.

function print(str, num) {
    Logger.log(str + ": " + num);
}

function test()
{
  var array = [1,2,3];
  var str = "Stam";
  //This line has an exception
  // TypeError: Cannot convert null to an object
  array.forEach(print.bind(null, str));
}
test();

this code is based on the solution described here.

I know there are other solutions, though i want to understand why this one does not work.

I wounder maybe it is not supported with google sheets.


回答1:


How about this answer? Please think of this as just one of several possible answers.

At Javascript, when null of bind(null, str) is used, this is used. At Google Apps Script, when null is used for bind(null, str), an error occurs like "Cannot convert null to an object". I think that this might be the specification of Google side. I'm not sure whether this is modified in the future update. So as the current workaround, how about using this instead of null? Or if you want to use bind(null, str) like null under the strict mode, how about using {} instead of null like bind({}, str)?

By the way, I think that test(); at the last line of your script can be removed. Because in your case, when test() is run at the script editor, test() is run 2 times by test(); at the last line. test(); at the last line is run as the global.

From above situation, when your script is modified, how about the following modification?

Modified script:

function print(str, num) {
  Logger.log(str + ": " + num);
}

function test() {
  var array = [1,2,3];
  var str = "Stam";
  array.forEach(print.bind(this, str));
}

or you can also modify test() of your script as follows. The following test() retrieves the same result with above one.

function test() {
  var array = [1,2,3];
  var str = "Stam";
  array.forEach(function(e) {print(str, e)});
}

Result:

When you run test() at the script editor, you can see the following result at the log.

Stam: 1
Stam: 2
Stam: 3

Reference:

  • Function.prototype.bind()

If I misunderstood your question and this was not the direction you want, I apologize.



来源:https://stackoverflow.com/questions/59635403/is-javascript-function-bind-supported-in-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!