Search code examples
javascriptoopdesign-patternsjavascript-objects

I want subobjects in JavaScript


I want to organize my JavaScript-Object in something like "submodules" and I wrote this:

'use strict';

var APS = (function () {

    var dashboard = (function () {
        var onReady = function () {
          alert(2);
        };

        return {
            onReady: onReady
        }
    });

    var onReady = function () {
        alert(1);
        dashboard.onReady(); // does not work
    };


    return {
        onReady: onReady,
    }
})();

$(document).ready(APS.onReady);

alert(1) does work, dashboard.onReady() does not work and I receive this error message:

Uncaught TypeError: dashboard.onReady is not a function

I want to organize my code in different "subpackages" below APS to have a kind of hierachy. How can I achieve that?


Solution

  • dashboard itself is a function that hasn’t returned the object containing onReady yet.

    Either complete the IIFE by adding another ():

    var dashboard = (function () {
        var onReady = function () {
          alert(2);
        };
    
        return {
            onReady: onReady
        }
    })(); // Calls as IIFE
    

    Or use dashboard().onReady instead.