[英]Passing arguments into the revealing Module pattern in Javascript
How can you pass arguments to a function when implementing the Revealing module pattern in JavaScript. 在JavaScript中实现Revealing模块模式时,如何将参数传递给函数。 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");
稍后,当我运行GlobalModule.consoleLog("Dummy text");
, I get undefined
as the output. ,我的输出undefined
。
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. 由于函数末尾的(),您正在导出consoleLog调用的结果,您希望在其中导出自身的函数。 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 object => function call
不需要返回对象
var GlobalModule ={ consoleLog: function(textToOutput) { console.log(textToOutput); } } GlobalModule.consoleLog("Dummy text");
Change the line 换线
consoleLog: consoleLog()
To 至
consoleLog: consoleLog
Or even(es6) to: 甚至(es6)可以:
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')
You you want to pass a global variable pass it in the parenthesis of the IIFE 您要传递全局变量,请在IIFE括号中传递它
var GlobalModule = (function(x) {
function consoleLog(textToOutput) {
console.log(textToOutput,x); // will log Hello temp
}
return {
consoleLog: consoleLog
};
})('temp');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.