如何在 JavaScript 中使用揭示模块模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5647258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:15:44  来源:igfitidea点击:

How to use Revealing module pattern in JavaScript

javascript

提问by theJava

I stumbled across this post: JavaScript's Revealing Module Pattern. I would like to use this in my project.

我偶然发现了这篇文章:JavaScript 的揭示模块模式。我想在我的项目中使用它。

Let's imagine I have a function abcand I am calling that function in my main JavaScript file.

假设我有一个函数abc,我在我的主 JavaScript 文件中调用该函数。

Does this pattern make things different? Can anyone show me a basic example of this pattern?

这种模式会让事情变得不同吗?任何人都可以向我展示这种模式的基本示例吗?

回答by KooiInc

A small example:

一个小例子:

var revealed = function(){
   var a = [1,2,3];
   function abc(){
     return (a[0]*a[1])+a[2];
   }

   return {
      name: 'revealed',
      abcfn: abc
   }
}();

in the anonymous function that is initiated to give revealeda value, aand abcare private to that function. What the function returns is an object literal with a nameproperty and a abcfnproperty, which is a reference to the abc function. The abc functionuses the private variable a. This can all be done thanks to the use of closures(everything within the scope of a function can be referenced by everything else in that same function).

在匿名函数中,该函数被启动以提供revealed一个值,a并且abc对该函数是私有的。该函数返回的是一个带有name属性和abcfn属性的对象字面量,它是对abc function. 在abc function使用私有变量a。这一切都可以通过使用闭包来完成(函数范围内的所有内容都可以被同一函数中的其他所有内容引用)。

Revealed usage:

显示用途:

alert(revealed.name);    //=> 'revealed'
alert(revealed.abcfn()); //=> 5 (1*2+3)

回答by Robert Koritnik

DC = Douglas Crockford
RMP = Revealing Module Pattern

DC = Douglas Crockford
RMP = 揭示模块模式

Difference between DC and RMP is mainly organizational/readable

DC 和 RMP 之间的区别主要是组织性/可读性

Example is presented in the article itself? And what exactly are you asking because those things don't have anything to do with files but rather to closures.

文章本身中提供了示例?你到底在问什么,因为这些东西与文件无关,而是与闭包有关。

You put everything in a closure (function) and expose only those part that you wish to be accessible. The difference between DC style and RMP is that in the first one functions are defined in different places while in the RMP they're always defined in the same place and then afterwards revealedin the publicobject literal.

您将所有内容都放在一个闭包(函数)中,并仅公开您希望访问的那些部分。DC的风格和RMP之间的区别是,在第一个功能在不同的地方被定义而在RMP,他们在同一个地方总是定义,然后再把显露公众对象文本。

So in the DC and RMP you have:

所以在 DC 和 RMP 中你有:

  • closure that makes it possible to define private parts (variables and functions)
  • private part
  • public result that defines publicly visible functionality and variables (state)
  • 可以定义私有部分(变量和函数)的闭包
  • 私处
  • 公共结果,定义公开可见的功能和变量(状态)

These two patterns differ only in readability. In DC case you can't always know where certain functionality will be defined, but in the RMP you always know everything is in the private part.

这两种模式仅在可读性上有所不同。在 DC 情况下,您不能总是知道某些功能将在哪里定义,但在 RMP 中,您总是知道一切都在私有部分。

回答by yojimbo87

Revealing module pattern is described pretty good in Essential JavaScript Design Patterns For Beginnersarticle.

揭示模块模式在Essential JavaScript Design Patterns For Beginners文章中描述得非常好。

回答by RobG

The method called by the author "Douglas Crockford's pattern for creating objects" is actually the module pattern that was developed mostly by Richard Cornford et al. See http://groups.google.com/group/comp.lang.javascript/msg/9f58bd11bd67d937

作者所称的“Douglas Crockford's pattern for created objects”实际上是Richard Cornford等人开发的模块模式。请参阅http://groups.google.com/group/comp.lang.javascript/msg/9f58bd11bd67d937

As for examples, there are many. Read the following article and follow some of the links: http://peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in-javascript-tm

至于例子,有很多。阅读以下文章并点击一些链接:http: //peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in-javascript-tm

回答by Maria Blair

Just want to add: with this pattern it's good to pass global dependencies as arguments/params so that they are explicit. You don't have to do it but this makes it very clear what your module needs from the first glance. E.g.:

只想补充一点:使用这种模式,最好将全局依赖项作为参数/参数传递,以便它们是显式的。您不必这样做,但这使您的模块从第一眼就很清楚需要什么。例如:

var myModule = (function ($, loadModule) {
  "use strict";
})(jQuery, load);

In this example, you can see right away in the 1st line that you module uses jQuery and some other module responsible for loading functionality.

在此示例中,您可以立即在第一行看到您的模块使用 jQuery 和其他一些负责加载功能的模块。

回答by Curt

I like to use a mixture of the revealing module patternwith the singleton patternso that I can keep structured code with the benefits of the module pattern:

我喜欢将揭示模块模式单例模式混合使用,以便我可以保持结构化代码与模块模式的好处:

var MyFunction = function(){

    var _ = {
       Init: function(){
          _.Config.foo = "hello world";
       },
       Config:{
          foo:null
       },
       ShowAlert:function(){
          alert(_.Config.foo);
       }
    }

    return {
        Init: _.Init,
        ShowAlert: _.ShowAlert
    };
}();

MyFunction.Init();
MyFunction.ShowAlert();

I've wrote more information on this on my blog:

我在我的博客上写了更多关于这个的信息:

http://curtistimson.co.uk/js/mixing-revealing-module-and-singleton-javascript-patterns/

http://curtistimson.co.uk/js/mixing-revealing-module-and-singleton-javascript-patterns/

回答by Sheo Dayal Singh

Here is the small example of revealing module pattern.

这是揭示模块模式的小例子。

It provides a facility to declare private and public functions just like a class.It is the major benefits of this patterns.If we do not want to expose some of the functionality accessible from globally then makes it private and rest of the make public.Below is the example how to make private and public functions.And one more things it is a self-executable block of code.

它提供了一个工具来声明私有和公共函数,就像一个类。这是这种模式的主要好处。如果我们不想公开一些可以从全局访问的功能,那么将其设为私有,其余的设为公有。下面是如何创建私有和公共函数的示例。另外,它是一个可自我执行的代码块。

  var Calculator = (function () {

        var num1 = 10;
        var num2=5
        var _abc = function () {
            return num1 - num2;
        };

        var _mulFunc = function () {
            return num1 * num2;
        };

        var _divFunc = function () {
            return num1/num2;
        };

        return {
           //public scope
            abc: _abc,
            mulFunc:_mulFunc
         };

    })();

alert(Calculator.abc()); it returns 5

警报(计算器.abc());它返回 5

alert(Calculator.mulFunc()); it returns 50

警报(计算器。mulFunc());它返回 50

And __divFunc() will not be accessible as it is in private scope. We can access only those functions which is declared inside return objectas it is public function representation

并且 __divFunc() 将无法访问,因为它在私有范围内。我们只能访问那些在return 对象中声明的函数, 因为它是公共函数表示

回答by Cody

The basic concept of a Revealing Module is that you have an Objectwhich encapsulatesits data and behavior:

揭露性模块的基本概念是,你有一个Object封装了数据和行为:

var Module = (function(){
    var privateStuff = {};
    var publicStuff = {};

    return publicStuff;
})();

However, there are some best practices you should employ when using this pattern. Here's a module ("Modulus") with some properties for demonstration sake, which employs some of these practices:

但是,在使用此模式时,您应该采用一些最佳实践。Modulus为了演示,这是一个带有一些属性的模块(“ ”),它采用了以下一些实践:

function AbstractSomeClass(id) {
    this.id = id;
    return this;
}

var Modulus = (new (function SomeClass() {
    var thus = this;

    function NameClass(name){
        this.value = thus.name || name;
    }

    AbstractSomeClass.call(this, 998);

    this.name = 'Touring';
    this.name = ( new NameClass('Hofstadter') ).value;

    return {
        id: this.id,
        name: this.name
    };
})());

Notice the (new (function SomeClass(){ ... })());syntax. Using newlike this allows you to use the thiskeyword insideof the closure. This is handy if you need to inherit properties from another class (AbstractSomeClass.call(this, 998);) -- However, you'll still need to revealthe properties that you would like to have public, e.g.:

注意(new (function SomeClass(){ ... })());语法。new像这样使用允许您在闭包使用this关键字。如果您需要从另一个类 ( )继承属性,这很方便——但是,您仍然需要显示您想要公开的属性,例如:AbstractSomeClass.call(this, 998);

return {
    id: this.id,
    name: this.name
};

Also notice that we assign thisto thus-- which allows us to use the Parent-thisinside of a subclass that has its own thisscope (this.value = thus.name || name;)

另请注意,我们分配thisthus-- 这允许我们this在具有自己的this作用域 ( this.value = thus.name || name;)的子类中使用 Parent-

Once again, these are just a few of the conventions and best practices that are suggested.

同样,这些只是建议的一些约定和最佳实践。

回答by Alex Wayne

To the code outside the module, it makes little difference. In all 3 cases in that article, the methods are called the same way. But the structure of the module itself is internally different.

对模块外的代码来说,差别不大。在该文章的所有 3 个案例中,方法的调用方式相同。但是模块本身的结构在内部是不同的。

Crockford's module pattern and what they call the "revealing module pattern" are pretty much the same thing, structurally. The only difference being that they assign the method to a local var first in order be more readable. But there really isn't anything special about it, and you have some examples right there in your link.

Crockford 的模块模式和他们所谓的“揭示模块模式”在结构上几乎是一样的。唯一的区别是他们首先将方法分配给本地 var 以便更具可读性。但实际上并没有什么特别之处,您的链接中有一些示例。