简体   繁体   English

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

[英]How to use Revealing module pattern in JavaScript

I stumbled across this post: JavaScript's Revealing Module Pattern .我偶然发现了这篇文章: JavaScript 的揭示模块模式 I would like to use this in my project.我想在我的项目中使用它。

Let's imagine I have a function abc and 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?任何人都可以向我展示这种模式的基本示例吗?

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 revealed a value, a and abc are private to that function.在开始给匿名函数revealed值, aabc是私有的该功能。 What the function returns is an object literal with a name property and a abcfn property, which is a reference to the abc function .该函数返回的是一个带有name属性和abcfn属性的对象字面abcfn ,它是对abc function的引用。 The abc function uses the private variable a . abc function使用私有变量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 usage:显示用途:

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

DC = Douglas Crockford DC = 道格拉斯·克罗克福德
RMP = Revealing Module Pattern 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 revealed in the public object 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 中,您始终知道一切都在私有部分。

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

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

I like to use a mixture of the revealing module pattern with the singleton pattern so 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/

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.您不必这样做,但这使您的模块从第一眼就很清楚需要什么。 Eg:例如:

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 和其他一些负责加载功能的模块。

https://www.realmelon.com/revealing-module-design-pattern-in-javaScript/ https://www.realmelon.com/revealing-module-design-pattern-in-javaScript/

I have written an article on it.我写了一篇关于它的文章。

You can have a look at this你可以看看这个

The basic concept of a Revealing Module is that you have an Object which encapsulates its 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(){ ... })());注意(new (function SomeClass(){ ... })()); syntax.句法。 Using new like this allows you to use the this keyword inside of the closure.使用new这样可以让你使用this封闭的内部关键字。 This is handy if you need to inherit properties from another class ( AbstractSomeClass.call(this, 998); ) -- However, you'll still need to reveal the properties that you would like to have public, eg:如果您需要从另一个类继承属性( AbstractSomeClass.call(this, 998);AbstractSomeClass.call(this, 998);这很方便——但是,您仍然需要显示您想要公开的属性,例如:

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

Also notice that we assign this to thus -- which allows us to use the Parent- this inside of a subclass that has its own this scope ( this.value = thus.name || name; )另请注意,我们分配thisthus -这使我们能够使用的父- this是有它自己的一个子类里面this范围( this.value = thus.name || name;

Once again, these are just a few of the conventions and best practices that are suggested.同样,这些只是建议的一些约定和最佳实践。

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());警报(计算器.abc()); it returns 5它返回 5

alert(Calculator.mulFunc());警报(计算器。mulFunc()); it returns 50它返回 50

And __divFunc() will not be accessible as it is in private scope.并且 __divFunc() 将无法访问,因为它在私有范围内。 We can access only those functions which is declared inside return object as it is public function representation我们只能访问那些在return 对象中声明的函数,因为它是公共函数表示

To the code outside the module, it makes little difference.对模块外的代码来说,差别不大。 In all 3 cases in that article, the methods are called the same way.在该文章的所有 3 个案例中,方法的调用方式相同。 But the structure of the module itself is internally different.但是模块本身的结构在内部是不同的。

Crockford's module pattern and what they call the "revealing module pattern" are pretty much the same thing, structurally. Crockford 的模块模式和他们所谓的“揭示模块模式”在结构上几乎是一样的。 The only difference being that they assign the method to a local var first in order be more readable.唯一的区别是他们首先将方法分配给本地 var 以便更具可读性。 But there really isn't anything special about it, and you have some examples right there in your link.但实际上并没有什么特别之处,您的链接中有一些示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM