簡體   English   中英

顯示模塊模式:在何處插入模塊訪問的變量

[英]Reveal module pattern: Where to insert variables for module access

我正在學習揭示模塊模式,我正在嘗試創建一個可重用的函數。 (在我的項目中,該函數將使頁面滾動。我不認為有必要在這里發布整個代碼。我只是把這個概念。)

基本概述是,有一個功能不會返回任何東西。 公共變量不需要。 這是代碼。 問題出在代碼中的注釋中:

的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'); 

Module Reveal Pattern提供私有和公共封裝。

下面是一些帶有一些解釋性注釋的例

有關JavaScript模式的更多信息模塊Reveal Pattern可以在這里找到

 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 

回答你的意見:

// 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 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

我希望它有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM