How to define global variable in Google Apps Script

后端 未结 6 2070
梦如初夏
梦如初夏 2020-11-30 03:23

I see most examples from Google is they use only functions in a single giant script.

e.g. https://developers.google.com/apps-script/quickstart/macros

But in

6条回答
  •  误落风尘
    2020-11-30 04:19

    In GAS global variables are not what they are in other languages. They are not constants nor variables available in all routines.

    I thought I could use global variables for consistency amongst functions and efficiency as well. But I was wrong as pointed out by some people here at SO.

    Global variable will be evaluated at each execution of a script, so not just once every time you run your application.
    Global variables CAN be changed in a script (so they are not constants that cannot be changed by accident), but will be reinitialized when another script will be invoked.
    There is also a speed penalty on using global variables. If within a function you use the same global variable two or more times, it will be faster to assign a local variable and use that instead.

    If you want to preserve variables between all functions in your application, it might be using a cacheService will be best. I found out that looping through all files and folders on a drive takes a LOT of time. But you can store info about files and folders within cache (or even properties) and speed up at least 100 times.

    The only way I use global variables now is for some prefixes and for naming widgets.

提交回复
热议问题