0

I am working with a bit of code which has the following Javascript function. I have read this SO article which has explained things a little bit but I am still a bit confused as to how this code works.

The code is as follows:

messageBus = (function() {
    var messages = {};

    function publish(name, data) {
        //does some stuff
    }

    function subscribe(name, callback) {
        //does some stuff
    }

    function unsubscribe(name, callback) {
        //does some stuff
    }

    return {
        publish:publish,
        subscribe:subscribe,
        unsubscribe:unsubscribe
    };
})();

And then is called by

messageBus.publish("Submit");

What does the

return {
    publish:publish,
    subscribe:subscribe,
    unsubscribe:unsubscribe
};

bit do in the code do?

Community
  • 1
  • 1
Jon Hunter
  • 882
  • 2
  • 8
  • 18
  • It returns an object with three properties `publish`, `subscribe` and `unsubscribe`. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers – Felix Kling Oct 29 '14 at 16:10
  • It returns an object. You can execute that code and look at messageBus in the console. – j08691 Oct 29 '14 at 16:10

2 Answers2

1

{} is an object literal.

{
    foo: bar
}

… is an object literal with a property called "foo" which has a value equal to the value of the variable "bar".

The function returns an object with three properties, where the values are the functions defined inside it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Because those three inner functions (publish, subscribe and unsubscribe) are declared inside another function, they wouldn't exist anywhere outside that outer function.

By returning that { ... } object with those three properties, you are effectively offering a 'public' API into the messageBusmessageBus will equal an object with properties of those 3 functions, so they can be called from the outer scope.

If the object wasn't returned, there would be no way to call those three inner functions from anywhere in the outer scope.

Shai
  • 7,159
  • 3
  • 19
  • 22