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();
1

1 Answer 1

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" );
Sign up to request clarification or add additional context in comments.

2 Comments

The "publicVar" isn't public, it's private. It's set by the privileged function publicSetName.
So it would exactly be same as using class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.