Search code examples
javascriptrevealing-module-pattern

Return in Revealing Module Pattern


I read Addy's book here about revealing module patter. However, if you execute the example code it actually returns undefined. A fix is to add 'return' before each called functions. Am I supposed to add return for each functions being called if using RMP? Is this the right way to make it work? What am I missing?

var myRevealingModule = (function () {

        var privateCounter = 0;

        function privateFunction() {
            privateCounter++;  <--need to add return
        }

        function publicFunction() {
            publicIncrement(); <-- need to add return
        }

        function publicIncrement() {
            privateFunction();  <--need to add return
        }

        function publicGetCount(){
          return privateCounter;
        }

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

       return {
            start: publicFunction,
            increment: publicIncrement,
            count: publicGetCount
        };

    })();

myRevealingModule.start(); <-return undefined 

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript


Solution

  • The issue nas nothing to do with RMP but rather with functions and return values.

    Why would you expect a method that doesn't return anything to actually return something other than undefined?

    Take a closer look here. The start in fact calls publicFunction but the body of the latter doesn't return anything.

    Yet you call it and expect a value.

    The answer to your question is then: yes, if you want a value back from the function, you have to return it.

    In this particlar example they have a method count to return current value. Two other methods are just used to control the counter.