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?
2 Answers 2
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 messageBus – messageBus 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.
Comments
{} 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.
publish,subscribeandunsubscribe. See developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…