Design patterns for libraries in GAS?

2019-07-21 14:36发布

问题:

I have been trying to figure out the best way to write GAS libraries for a while now but I have a hart time figuring it out. I read Douglas Crockford's - Javascript: The good parts and I'm trying to implement these lessons in GAS. Every imported library adds global variable to your project (of the ScriptModule type), so the modular design pattern seems like a good place to start. Borrowing from the article I linked to such a pattern might look like this:

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

This module could then be called like this:

var module = LibName.MODULE;
var property = module.moduleProperty; // 1
var method = module.moduleMethod; // ...

From what I gather it is best have as few global variables as possible, so the general advice seems to be to save everything in one global variable. So the naming convention should then look something like this: LibName.PROJECT_NAME, where project name is the name of your single global variable which holds a module with everything else.

My goal here is to design secure, non-conflicting libraries. Am I right to use this design pattern? Has anyone developed their own robust design patterns for GAS libraries yet?

回答1:

When you import a script as a library in GAS a new "namespace" is already created for it, so there's no need or gain in creating another one yourself. You'd have have to "deference" it, like you did:

//there's no purpose for this
var module = LibName.MODULE;
var method = module.method;

//comparing if you write code directly on the library
var method1 = LibName.method1;

GAS is not client-side javascript, most of things you learn don't really apply to Apps Script, e.g. there's no DOM, no namespace conflict, no browser compatibility issues, etc.

By the way, I don't think this object nesting structure even works on Apps Script libraries.