-1

I am doing a school assignement where we have to do a small application which manage a monster by following a pattern but my lesson is very badly explained so I understand nothing, I can't make the difference between public and private, I know what is the difference in Java, Php but not in js.

Here is what it does, when I load the page, it execute run() in monster.modules.app and this should execute showMe() in monster.modules.actions, the problem is I get this TypeError: monster.modules is undefined..

So can you explained me why I can't access to monster in this public or private function ?

And why do I have to put functions into parenthesis ?

(function (glob) {

    /**
     * Etape 1.1
     */
    // NAMESPACE : monster
    var monster = monster || {
            modules: {}
        };

    /**
     * Etape 1.2
     */
    monster.modules.actions = (function () {
        /**
         * Etape 1.2.1
         */
        var name;
        var life;
        var money;
        var awake;

        return {
            /**
             * Etape 1.2.2
             */
            showMe: function () {
                alert('Monster ' + this.name + ' : {life : ' + this.life + ', money : ' + this.money + ', awake : ' + this.awake + ' }');
            },

            /**
             * Etape 1.2.3
             */
            init: function (name, life, money, awake) {
                this.name = name;
                this.life = life;
                this.money = money;
                this.awake = awake;
            }
        };

    })();

    /**
     * Etape 1.3
     */
    monster.modules.app = (function () {
        /**
         * Etape 1.3.1
         */
        var show = document.getElementById('b6');

        return {
            /**
             * Etape 1.3.2
             */
            run: (function () {
                console.log('run');
                show.onclick = (function () {
                    monster.modules.actions.showMe();
                });

            })
        };
    })();

    /**
     * Etape 1.3.4
     */
    window.onload = (function () {
        monster.modules.app.run();
    });


})(window);
georg
  • 211,518
  • 52
  • 313
  • 390
oktomus
  • 566
  • 7
  • 28

1 Answers1

1

Actually you don't wrap every function in parenthesis like this

myIIF = (function { ... });

You can put them in parenthesis if you invoke them immediately, this type of function is called Immediately Invoked Functions or IIF:

myIIF = (function { ... })();

By invoking functions that way you create a so called closure, a function within a function to create a new scope.

You can find a straighforward explanation of closures here