Two teeny-tiny changes fix the "MyComany is undefined error" and a syntax error on the menus variable declaration.
- Assign directly an empty object instead of using the short-circuit object assignation on the MyCompany variable declaration
- The value assigned to the menu item
functionName
property should be a string.
MyCompany = {};
MyCompany.init = function () {
Logger.log('init');
};
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menus = [{
name: "Init",
functionName: "MyCompany.init"
}];
spreadsheet.addMenu("Test", menus);
};
Another way to declare a namespace
const MyCompany = (ns => {
ns.init = function () {
Logger.log('init');
return ns;
}({});
About Global Variables in Google Apps Script
Some previous answers have warned that global variables don't work as commonly expected based on experience working with JavaScript on other platforms.
The key is to understand that each call of the Google Apps Script function from a custom menu, Google Sheets image with an assigned function, dialog, sidebar or web application using the HTML Service, trigger, the Apps Script editor or the Google Apps Script API will load the whole Apps Script project into the Google Apps Script execution engine.
If you use the globally declared variables on a single execution, there should not be problems, as the code is written properly. However, if you need to keep the object and values assigned to the variables across multiple executions, then you have to save those values somewhere other than the runtime memory.
There are several options
- Properties Service.
- Cache Service.
- An external database using the JDBC Service
- A Google Sheets spreadsheet using the Spreadsheet or the Advanced Sheets services.
- A Google Drive file using the Drive or the Advanced Drive services.
- Etc.
Related
var
:var MyCompany = (MyCompany || {});
– Rinconvar
works. – Jozef