javascript - 显示模块模式 : Where to insert variables for module access

标签 javascript design-patterns

我正在学习揭示模块模式,并且我正在尝试创建一个可重用的函数。 (在我的项目中,该函数将使页面滚动。我认为没有必要在这里发布整个代码。我只是提出概念。)

基本概述是,有一个函数不会返回任何内容。不需要公共(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/

相关文章:

javascript - 带有外部 CSV 的 Highchart(在外部域中)

javascript - jQuery 不会动画

c++ - 将 this 传递给 this 的类变量的方法

javascript - 具有约束的数据动态聚合

javascript - 当我将员工状态更改为终止或辞职时,添加另一个字段辞职日期

javascript - Vuejs 源代码中的静态类型检查

javascript - Facebook Sharer - 标题和摘要自定义

c++ - 向更新其物理状态的对象添加数值积分

c++ - 这种模式如何运作?

c# - 如何对存在于所有限界上下文中并且是应用程序核心部分的实体进行建模?