最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Passing arguments into the revealing Module pattern in Javascript - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 14, 2017 at 11:44 cross19xxcross19xx 3,4872 gold badges27 silver badges41 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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
};

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");

Change the line

consoleLog: consoleLog()

To

consoleLog: consoleLog

Or even(es6) to:

consoleLog

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');
发布评论

评论列表(0)

  1. 暂无评论