23

Ok, I feel embarrassed that I wasn't able to figure this out on my own, but after a few wasted hours, I figured it would be easier to simply ask over here:

I have a bunch of .gs-files in my Google Apps Script project. Now, I want to call another file's function from a method (something like AnotherClass.awesomeFunction(), which throws a ReferenceError though). Is this possible in Google Apps Script? If so, how?

TomTasche
  • 5,448
  • 7
  • 41
  • 67

5 Answers5

40

Files aren't classes. You can call any functions in any file from any other file. Think of your files as if they were just added together before running. If you want class-like scoping you can use the Libraries feature.

Corey G
  • 7,754
  • 1
  • 28
  • 28
6

The Above replies are correct above file being appended, make sure the order of the files in the file explorer on the app script project page is correct

The Function definition should be in the first file and the function call in the latter.

You change the option of the each file by clicking the 3 dots next to file name and selecting Move file up or Move file down

Rathil Vasani
  • 61
  • 1
  • 2
2

The following syntax allows you to call any function from within your Google Apps Script project, regardless of whether the function is defined in the same file that is calling it:

myFunction();

The following code is unnecessary and will throw errors:

google.script.run.myFunction();
user971732
  • 25
  • 1
  • 5
Ben F
  • 31
  • 2
1

I'd just like to add that order of files is not important as experienced by me so far. I'm working on a project where all calls are at the start to get a clear tree and all definitions of functions are at the end. Sometimes they're even mixed without any order within files too. So, I guess, it can call function from anywhere regardless of order within file or within project files. It's working in my case though.

Cian
  • 37
  • 6
0

It can do.

and Corey is right, files is not class.

Sam
  • 105
  • 2
  • 14