Search code examples
javascriptfunctiongoogle-apps-scriptparentsiblings

How to invoke a function from both an outside and a sibling function in javascript / google app script


Basic question but I can't figure it out :(. A solution to one makes the other one break. Here is the specific case narrowed down, any help is appreciated.

function onOpen() { // first entry point
    var helper = new level1Function();
    helper.level2FunctionA();
}

function onFormSubmit() { // second entry point
    var helper = new level1Function();
    helper.level2FunctionC();
}

function level1Function() {

    this.level2FunctionA = function() {
        console.log('hi');
    }

    function level2FunctionB() { 
        // how do I invoke level2FunctionA from here w/o breaking onOpen entry point?
    } 

    this.level2FunctionC = function() { 
        level2FunctionB(); 
    } 
}

onOpen();
onFormSubmit();
// looking for 2 hi's to the console, one through each flow

Solution

  • create a reference to a variable self, assign to this at the top of the function body

    function level1Function() {
    
        var self = this;
    
        this.level2FunctionA = function() {
            console.log('hi');
        }
    
        function level2FunctionB() { 
            self.level2FunctionA();
        } 
    
        this.level2FunctionC = function() { 
            level2FunctionB(); 
        } 
    }