我正在学习揭示模块模式,我正在尝试创建一个可重用的函数。 (在我的项目中,该函数将使页面滚动。我不认为有必要在这里发布整个代码。我只是把这个概念。)
基本概述是,有一个函数不会返回任何内容。公共变量不需要。这是代码。问题出在代码中的注释中:
var MyModule = (function() {
// Is this the correct place to insert the
// variables that will be used throughout 'MyModule'?
var foo = 'foo',
foo2 = 'foo2',
param1 = null;
var MyModule = function(_param1) {
param1 = _param1;
logParam();
};
function init() {
foo = 'something';
}
function logParam() {
console.log(param1);
}
init();
return MyModule;
})();
var module = new MyModule('Some Paramater');
// Is this okay? Does it still follow reveal module pattern?
MyModule('Some Other Paramater');
// Or do I always have to do like this:
var module = new MyModule('Some Paramater');
答案 0 :(得分:0)
Module Reveal Pattern提供私有和公共封装。
下面是一个带有一些解释性评论的例子。
有关JavaScript模式的更多信息可以找到模块显示模式here
var myRevealingModule = (function () {
// below are private variables and functions that are not accessible outside the module this is possible thanks to a javascript closure
var privateVar = "Ben Cherry",
publicVar = "Hey there!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
// below are public functions, they will be publicly available as they are referenced in the return statement below
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
myRevealingModule.setName( "Paul Kinlan" );
console.log(myRevealingModule.greeting);// public
console.log(myRevealingModule.getName());// public
//console.log(myRevealingModule.privateFunction());// private, you cannot access it

答案 1 :(得分:0)
回答你的意见:
// Is this okay? Does it still follow reveal module pattern?
MyModule('Some Other Paramater');
是的,没关系。如果你想要你的揭密模块模式" MyModule "必须是自我封闭的:
var MyModule = function(param1) {
var myPlublicFunction = function(){
}
return {
myPlublicFunction: myPlublicFunction
};
}(); //selfclosing
OR
// Or do I always have to do like this:
var module = new MyModule('Some Paramater');
如果您需要,您的揭密模块模式" MyModule "必须不是自我封闭:
var MyModule = function(param1) {
var myPlublicFunction = function(){
}
return {
myPlublicFunction: myPlublicFunction
};
}; // not selfclosing
我希望它有所帮助