[英]Why do I get Uncaught ReferenceError: scrollToM is not defined?
[英]Why do I get “ReferenceError: test is not defined”
在我的谷歌腳本項目中,我得到了兩個 GS 文件Code.gs
和other.gs
。
code.gs 看起來像
var globalSettings = {};
settings();
function settings(){
other();
globalSettings.fileName = "file";
console.log("settings was executed");
}
function primary(){
console.log("primary was executed");
}
other.gs 看起來像
function other(){
console.log("other was executed");
}
當我運行 function primary
時,我得到
ReferenceError: other is not defined
settings @ Code.gs:5
(anonymous) @ Code.gs:1
當我將 function other
移動到文件code
時,它可以工作。 有人可以解釋為什么嗎? 有沒有辦法讓其他文件在項目中的任何地方?
每次調用 function(在項目中的任何腳本中)時,都會自動執行全局變量。
這就是為什么如果您將var globalSettings = {}
定義為全局 decleration,每次您在項目中運行任何 function 時,都會執行所有全局調用,因此globalSettings
將設置為空 object 這就是我不這樣做的原因t 使用全局變量。
全局調用other
和function decleration other
需要在同一個gs
腳本中才能工作。 或者您可以簡單地從功能settings
或primary
函數中調用other
,這樣other
可以保留在單獨的腳本中。
例如,這會很好地工作:
code.gs
// define global variables
var globalSettings = {};
// adjust global variables here as a helper function
function settings(){
other();
globalSettings.fileName = "file";
console.log("settings was executed");
}
// main function to be executed
function primary(){
settings(); // call settings
console.log(globalSettings.fileName);
console.log(globalSettings.date);
console.log("primary was executed");
}
other.gs
// make additional adjustments to the global variables
function other(){
globalSettings.date = "today";
console.log("other was executed");
}
建議:
確保不執行全局聲明的更好方法是使用 Class PropertiesService class 來存儲一些腳本或用戶數據,然后您可以全局或本地(在函數內部)檢索它們,這將確保您不會像全局聲明那樣在每次執行時意外執行它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.