admin管理员组文章数量:1327993
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.
4 Answers
Reset to default 4return {
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');
本文标签: Passing arguments into the revealing Module pattern in JavascriptStack Overflow
版权声明:本文标题:Passing arguments into the revealing Module pattern in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742236231a2438130.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论