2

How can you pass arguments to a function when implementing the Revealing module pattern in JavaScript. I have a module like this

var GlobalModule = (function() {
    function consoleLog(textToOutput) {
        console.log(textToOutput);
    }

    return {
        consoleLog: consoleLog()
    };
})();

Later on, when i run GlobalModule.consoleLog("Dummy text");, I get undefined as the output.

cross19xx
  • 3,170
  • 1
  • 25
  • 40

4 Answers4

4
return {
    consoleLog: consoleLog()
};

That part of your code is wrong. You're exporting the Result of the consoleLog call due to the () at the end of the function, where you want to export the function itsself. So just remove the function call:

return {
    consoleLog: consoleLog
};
Shilly
  • 8,511
  • 1
  • 18
  • 24
2

Do with function inside the return object

var GlobalModule = (function() {
  return {
    consoleLog: function(textToOutput)
    {
     console.log(textToOutput);
    }
  }
})();

GlobalModule.consoleLog("Dummy text");

Simply Do like this same output achieved . object => function call .No need a return object

 var GlobalModule ={
        consoleLog: function(textToOutput) {
                                    console.log(textToOutput);
                                  }
      }

    GlobalModule.consoleLog("Dummy text");
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • but what if you don't want to invoke a method or property of the module, i.e. i want to do `myRevealingModule('my-string')`, and not `myRevealingModule.doSomething('my-string')`. – Ronnie Royston Sep 04 '17 at 20:01
  • @RonRoyston you need a direct function call.[see this fiddle](https://jsfiddle.net/poosanth/coshzhra/) – prasanth Sep 05 '17 at 05:15
2

Change the line

consoleLog: consoleLog()

To

consoleLog: consoleLog

Or even(es6) to:

consoleLog
Cristóvão Trevisan
  • 1,775
  • 17
  • 18
1

You can do like this

var GlobalModule = (function() {
    function consoleLog(textToOutput) {
        console.log(textToOutput);
    }

    return {
        consoleLog: consoleLog // () is removed otherwise it will execute immediately
    };
})();

GlobalModule.consoleLog('Hello')

DEMO

You you want to pass a global variable pass it in the parenthesis of the IIFE

var GlobalModule = (function(x) {
    function consoleLog(textToOutput) {
        console.log(textToOutput,x); // will log Hello temp
    }
   return {
        consoleLog: consoleLog
    };
})('temp');
brk
  • 48,835
  • 10
  • 56
  • 78