0

Just out of pure curiosity I have seen codes like below

let GlobalActions = function () {

    let doSomething= function () {
        //Do Something
    };

    return {
        doSomething: function () {
            doSomething()
        }
    };
}();

GlobalActions.doSomething();

At first, I thought it was about scoping, maybe var declared variables from outside is not accessible from each functions inside after it has been initialized; however, that was not true.

Then it came to me thinking what is the advantage of doing the above instead of the below?

let GlobalActions = {

    doSomething: function () {
        //Do Something
    };

};

GlobalActions.doSomething();
forJ
  • 4,309
  • 6
  • 34
  • 60
  • This is the so-called "module pattern" that is used for private members, see [*Private Members in JavaScript*](https://crockford.com/javascript/private.html). There are [*many, many questions here already*](https://stackoverflow.com/search?q=%5Bjavascript%5D+module+pattern) (so this is likely a duplicate of some of them, maybe [*why module pattern?*](https://stackoverflow.com/questions/7471349/why-module-pattern)). – RobG Jan 03 '18 at 03:14

1 Answers1

1

Looks to me like The Revealing Module Pattern.

Essentially the returned object provides the "API" interface to the entire class. We can then choose what is exposed as public and what remains private. Eg.

var myRevealingModule = (function () {

        var privateVar = "Ben Cherry",
            publicVar = "Hey there!";

        function privateFunction() {
            console.log( "Name:" + privateVar );
        }

        function publicSetName( strName ) {
            privateVar = strName;
        }

        function publicGetName() {
            privateFunction();
        }

        // Reveal public pointers to
        // private functions and properties

        return {
            setName: publicSetName,
            greeting: publicVar,
            getName: publicGetName
        };

    })();

myRevealingModule.setName( "Paul Kinlan" );
Bradley Flood
  • 10,233
  • 3
  • 46
  • 43