Search code examples
google-apps-scriptgoogle-sheetsidejavascript-objects

Apps Script: why does name of properties cause "Maximum call stack size exceeded"?


  • I'm using Apps Script to customize my Google Sheets;
  • I have two different objects (one is private, the other one is public) with same properties;
  • They interact with each other;
  • Here follows an example:
function run(argument) {
    let Public  = {}
    let Private = myClass().setFoo(argument)

    Public.getFoo = Private.getFoo
    return Public;
}

function myClass() {
    let Public  = {};
    let Private = {};
    
    Private.foo = null;

    Public.setFoo = function (arg) { Private.foo = arg; return Public};
    Public.getFoo = function ()    { return Private.foo };
    return Public;
}
  • I don't want setter to be available to the coder. That's why I'm doing this pattern;
  • The problem is: when I run it (through other function somewhere), the log displays: "Maximum call stack size exceeded", pointing to the Public.getFoo = Private.getFoo;
  • I've tried many ways to solve this, but the only thing that worked was changing the properties names, like Public.getFoo = Private._getFoo

It seams like Apps Script IDE understand both of them are the same object, so it would call itself infinetely. But why does that happen if I'm not referring to the same object?


Solution

  • Years later, after reviewing this project, I've come to some conclusions:

    • There are better ways to protect methods or values from being visible and accessible. I could've made use of simple code like:
    function runMe() {
        const obj = createObject();
        obj.setValue('foo'); //logged value:'foo'
      
        console.log(obj.privateValue); //throws error (not acessible)
    };
    
    function createObject() {
        let privateValue = null;
        return { setValue:(arg)=>{/* sets value and logs it */} }
    };
    
    runMe();
    
    • Sometimes, less is more; and that's clear now that I'm able to realize the final effect I desired back then was essentially the same produced by the example given above;
    • I remember seeking for patterns, in an attempt to acquire knowledge I felt was mandatory and made me write prolix code. It wasn't necessary, indeed; I already had everything I needed with me. So one advice is: go simple, especially if you're not deploying add-ons and WebApps;

    The article suggested by @David Salomon, in the previous answer, written by Basti Ortiz, was insanely helpful at that time. Thanks, David!