问题描述
如果我在一个Apps脚本项目中有多个文件,它们具有一个具有相同名称的函数,那么如何确定范围?
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?
- 按文件?
- 通过动态范围界定吗?
- 通过静态作用域?
- 创建函数的时间(创建脚本文件)?
例如,如果我有 Stuff.gs :
function start() {
var number = getNumber();
}
function getNumber() {
return 5;
}
和更多.gs :
function getNumber() {
return 10;
}
我打电话给start()
,Google的平台如何确定要调用哪个函数?
And I call start()
, how does Google's platform determine which function to call?
我做了这样的测试,但没有得到预期的输出.输出为10.0
.在我看来,既没有应用文件作用域规则,也没有应用静态作用域.我创建了第三个文件以进一步测试:
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;
}
,现在输出为15.0
.我进一步进行了测试,并在 More.gs 中将 10 更改为 20 ,以查看是否保存了时间戳确定了范围,但是输出仍然是15.0
.
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
.
在我看来, .gs 文件的创建日期确定了范围-使用了包含函数名称的文件上的最新时间戳.我的假设是正确的还是只是巧合,还是通过其他方式确定的?
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?
这还专门针对Google的Apps脚本或Javascript吗?
Also, is this specific to Google's Apps Script, or Javascript in general?
推荐答案
这些声明看起来都在全局范围内.后续的定义将覆盖先前的定义,因此,如果您先包含Stuff.gs
,然后包含More.gs
,然后包含Test.gs
,然后再调用您的函数,则将是有意义的.
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.
JS中的作用域是静态的(假定没有with
和本地eval
的严格模式),但是可以根据加载的模块(及其顺序)动态修改全局范围.这是大多数JavaScript环境中的行为,有些还具有其他文件(模块)作用域.
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.
这篇关于功能范围规则(Google Apps脚本项目)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!