0

I have read a bunch on closures, and for the most part understand the basic concept. That said, can someone explain the following snippet of code as far as where the closures are created and what the difference between returning a function and returning an object.

    return function () {
        var topics = {};

        return {
            subscribe: function (topic, listener) {
                if (listener && typeof (listener) === 'function') {
                    topics[topic] = topics[topic] || { queue: [] };
                }

                var index = topics[topic].queue.push(listener) - 1;

                return (function (topic, index) {
                    return {
                        remove: function () {
                            delete topics[topic].queue[index];
                        }
                    }
                })(topic, index);
            },
            publish: function (topic, info) {
                if (!topics[topic] || !topics[topic].queue.length) return;

                angular.forEach(topics[topic].queue, function (listener) {
                    listener.apply(this, info);
                });
            }
        };
    };
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Sam
  • 15,336
  • 25
  • 85
  • 148
  • `return function () {` not a good idea to start with a syntax error. A return statement can't appear outside a function. – RobG Jun 25 '14 at 02:58
  • The difference between returning a function and returning an object is... pretty straight-forward, no? An object is an object, a function is a function. (And functions are also objects. But I don't think that's what you're asking.) – Dave Newton Jun 25 '14 at 03:02

0 Answers0