Search code examples
javascriptmoduleself-invoking-function

Why is my javascript module returning undefined when I try to access variables?


I have a javascript module that neatly separates data from dom and returns a public api for its data and ui objects:

var PtCalcApp = (function() {
    var ptCalc = ptCalc || {};

    ptCalc.ui = {
        storage: $('#pt-storage'),
        backup: {
            daily: $('#per-day-data'),
            weekly: $('#per-week-data'),
            monthly: $('#per-month-data'),
            yearly: $('#per-year-data')
        },
        change: {
            yearly: $('#annual-change'),
            daily: $('#daily-change')
        }
    };

    ptCalc.data = {
        storage: function() {
            ptCalc.ui.storage.val()
        }
    }

    return ptCalc;
})();

Now when I try to access data like this this:

PtCalcApp.data.storage()

it returns undefined. What am I doing wrong with this self invoking function pattern? How do I fix this?


Solution

  • You are not returning anything from the function. Without a return statement, the function will return undefined (unless called with new, but that's a different matter).

    storage: function() {
        ptCalc.ui.storage.val()
    }
    

    should be

    storage: function() {
        return ptCalc.ui.storage.val()
    }