Function Scope Rules (Google Apps Script Project)

2019-07-18 23:37发布

If I have several files in a single Apps Script Project that have a function with the same name, how will the scope be determined?

  • By file?
  • By dynamic scoping?
  • By static scoping?
  • Time of function creation (script file created)?

For example if I have Stuff.gs:

function start() {
  var number = getNumber();
}

function getNumber() {
  return 5;
}

and More.gs:

function getNumber() {
  return 10;
}

And I call start(), how does Google's platform determine which function to call?

I did a test like this, and I didn't get the expected output. The output is 10.0. It seems to me that neither file scope rules are applied, nor static scoping. I created a third file to test further:

Test.gs:

function getNumber() {
  return 15;
}

and now the output is 15.0. I further tested and changed 10 to 20 in More.gs to see if the save timestamp determined the scope, but the output was still 15.0.

So to me it seems that the .gs file creation date determines the scope - the most recent timestamp on the file that contains the function name is used. Am I correct in my assumption or is this just a coincidence and it's determined in some other way?

Also, is this specific to Google's Apps Script, or Javascript in general?

1条回答
贼婆χ
2楼-- · 2019-07-19 00:17

Looks like those declarations are all just in global scope. Subsequent definitions will overwrite the previous ones, so if you are first including Stuff.gs, then More.gs, then Test.gs and are calling your function thereafter it would make sense.

The scoping in JS is static (assuming strict mode without with and local eval), but the global scope may be modified dynamically based on the loaded modules (and their order). This is the behaviour in the most JavaScript environments, some also have an additional file (module) scope.

查看更多
登录 后发表回答