我正在学习揭示模块模式,并且我正在尝试创建一个可重用的函数。 (在我的项目中,该函数将使页面滚动。我认为没有必要在这里发布整个代码。我只是提出概念。)
基本概述是,有一个函数不会返回任何内容。不需要公共(public)变量。这是代码。问题在代码中的注释处:
JSFiddle
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');
最佳答案
The Module Reveal Pattern provides both private and public encapsulation.
下面是一个带有一些解释性注释的示例。
有关包含模块显示模式的 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
关于javascript - 显示模块模式 : Where to insert variables for module access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500195/