为什么是模块模式?[英] why module pattern?

本文是小编为大家收集整理的关于为什么是模块模式?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我已经阅读了很多有关模块模式的内容. 好的,它带来了结构,私人方法等... 但是有了以下代码,我可以不使用它来获得相同的行为.

function Human()
{
  // private properties
  var _name='';
  var _age=0;


  // private methods
  function created()
  {
    console.log("Human "+_name+" called");
  };

  // public
  this.setName = function(name){
    _name=name;
    created(); 
  };

}


var h1 = new Human();

h1.setName("John");

那么,最终模块模式的真正优势是什么?

推荐答案

我认为此示例可以帮助您澄清模块模式的有用性.

模块模式

模块模式被广泛使用,因为它提供了结构并有助于组织 随着代码的增长.与其他语言不同,JavaScript没有特殊的语法 对于包装,但是模块模式提供了创建独立脱钩的工具 可以将其视为黑盒功能性并添加的代码片段, 根据软件的(不断变化的)要求替换或删除 您正在写作.

模块图案是几种模式的组合,即:

  • 名称空间
  • 立即功能
  • 私人和特权成员
  • 声明依赖项

第一步是设置一个名称空间.让我们使用早期的 namespace()函数 在本章中,启动一个提供有用数组方法的实用程序模块:

MYAPP.namespace('MYAPP.utilities.array');

下一步是定义模块.该模式使用即时功能将 如果需要隐私,则提供私人范围.即时函数返回一个对象 - 带有公共接口的实际模块,该模块将可用于消费者的消费者 模块:

 MYAPP.utilities.array = (function () {
    return {
    // todo...
    };
 }());

接下来,让我们在公共接口中添加一些方法:

MYAPP.utilities.array = (function () {
   return {
      inArray: function (needle, haystack) {
         // ...
      },
      isArray: function (a) {
         // ...
      }
   };
}());

使用即时功能提供的私人范围,您可以声明一些 根据需要的私人属性和方法.就在即时功能的顶部 也将是声明您的模块可能拥有的任何依赖项的地方.下列的 变量声明,您可以选择放置任何一次性初始化代码 帮助设置模块.最终结果是立即函数返回的对象 其中包含模块的公共API:

MYAPP.namespace('MYAPP.utilities.array');
MYAPP.utilities.array = (function () {
   // dependencies
   var uobj = MYAPP.utilities.object,
       ulang = MYAPP.utilities.lang,
       // private properties
       array_string = "[object Array]",
       ops = Object.prototype.toString;
       // private methods
       // ...
       // end var
   // optionally one-time init procedures
   // ...
   // public API
   return {
      inArray: function (needle, haystack) {
         for (var i = 0, max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
               return true;
            }
         }
      },
      isArray: function (a) {
         return ops.call(a) === array_string;
      }
      // ... more methods and properties
   };
}());

模块图案是一种广泛使用的,强烈建议组织 代码,尤其是随着它的生长.

" JavaScript模式,Stoyan Stefanov (O’Reilly).版权2010 Yahoo!,Inc.,9780596806750

其他推荐答案

不确定为什么没有人能正确回答这个问题.我可以看到使用某种模式使用自动驱动功能的潜力,旨在使私有var可以继承,但您绝对正确.

使用模块模式代替核心语言函数构造函数没有好处.这是相同的精确语言机械师(封闭),允许仅使用更多代码作为不可访问的实体存在持久性内部var.

在JS中,功能构造函数遵循与射击功能相同的范围规则.范围和闭合设置为定义点.来自函数构造函数的内部var依据的原因是因为具有在同一构造函数中定义的实例引用了VAR依靠的实例.

唯一变化的是,您已经消除了构造函数上原型方法的使用,并且必须陪审团陪审员您自己的继承机制.

其他推荐答案

庞大的JavaScript项目正在构建使用模块模式,也许您有自己的想法,并希望确保您的代码易于阅读且结构良好. 通过学习几个模式,您可以使您的应用程序更易于构建和维护. 这些模式是由最有才华的开发人员使用的,例如,人们构建节点JS,jQuery,Bootstrap,Angular等. 简单示例:

  function foo (){
    console.log("foobar");
};

foo();

当我们调用这种简单的方法时,我们会注意到它可以在全球名称空间中访问,当我们谈论大型应用程序时,这是一个巨大的问题.

这有时我们将其称为混乱的全球名称空间. 这是一个问题的原因是因为浏览器中发生了很多事情,您可能会在浏览器中加载Angular,Bootstrap和jQuery,您甚至可能还有其他一些JavaScript库. 现在,如果您必须浏览一堆混乱的全局名称空间的变量,那么这可能是没有意义的.实际上,如果您创建的变量共享与另一个库中的变量相同的名称相同的名称,则甚至可能是灾难性的. 最基本的模块模式将解决此问题.为此,我在自我执行的匿名函数中描述了我的代码,现在看起来像这样: 由此:

function foo (){
    console.log("foobar");
};

foo();

:

(function(){function foo (){
    console.log("foobar");
};

foo();
}());

我们包装一个函数enclosure(),然后我可以称呼它,需要包装函数的原因是因为没有名称的函数本身会返回未定义这整个内容是立即评估的表达式,不一定需要命名或分配,现在我们运行代码并检查浏览器时,我们将看到现在,现在全局名称空间与我的变量不混乱.我们可以看到foo不确定.

源树屋研讨会有关JavaScript中基础模块模式的研讨会

本文地址:https://www.itbaoku.cn/post/627638.html

问题描述

I've read a lot of things about the module pattern. Ok It brings structure, private method, etc... But with the code below I can get the same behavior without using it.

function Human()
{
  // private properties
  var _name='';
  var _age=0;


  // private methods
  function created()
  {
    console.log("Human "+_name+" called");
  };

  // public
  this.setName = function(name){
    _name=name;
    created(); 
  };

}


var h1 = new Human();

h1.setName("John");

So, what are the real advantage of a module pattern finally ?

推荐答案

I think this example could help you to clarify the usefulness of the Module Pattern.

Module Pattern

The module pattern is widely used because it provides structure and helps organize your code as it grows. Unlike other languages, JavaScript doesn’t have special syntax for packages, but the module pattern provides the tools to create self-contained decoupled pieces of code, which can be treated as black boxes of functionality and added, replaced, or removed according to the (ever-changing) requirements of the software you’re writing.

The module pattern is a combination of several patterns, namely:

  • Namespaces
  • Immediate functions
  • Private and privileged members
  • Declaring dependencies

The first step is setting up a namespace. Let’s use the namespace() function from earlier in this chapter and start an example utility module that provides useful array methods:

MYAPP.namespace('MYAPP.utilities.array');

The next step is defining the module. The pattern uses an immediate function that will provide private scope if privacy is needed. The immediate function returns an object - the actual module with its public interface, which will be available to the consumers of the module:

 MYAPP.utilities.array = (function () {
    return {
    // todo...
    };
 }());

Next, let’s add some methods to the public interface:

MYAPP.utilities.array = (function () {
   return {
      inArray: function (needle, haystack) {
         // ...
      },
      isArray: function (a) {
         // ...
      }
   };
}());

Using the private scope provided by the immediate function, you can declare some private properties and methods as needed. Right at the top of the immediate function will also be the place to declare any dependencies your module might have. Following the variable declarations, you can optionally place any one-off initialization code that helps set up the module. The final result is an object returned by the immediate function that contains the public API of your module:

MYAPP.namespace('MYAPP.utilities.array');
MYAPP.utilities.array = (function () {
   // dependencies
   var uobj = MYAPP.utilities.object,
       ulang = MYAPP.utilities.lang,
       // private properties
       array_string = "[object Array]",
       ops = Object.prototype.toString;
       // private methods
       // ...
       // end var
   // optionally one-time init procedures
   // ...
   // public API
   return {
      inArray: function (needle, haystack) {
         for (var i = 0, max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
               return true;
            }
         }
      },
      isArray: function (a) {
         return ops.call(a) === array_string;
      }
      // ... more methods and properties
   };
}());

The module pattern is a widely used and highly recommended way to organize your code, especially as it grows.

“JavaScript Patterns, by Stoyan Stefanov (O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750

其他推荐答案

Not sure why no one's answered this one properly. I can see potential for using auto-invoking functions in some kind of pattern meant to make private vars inheritable, but you're absolutely right.

There is no benefit to using the module pattern in place of a core language function constructor. It's the same exact language mechanic (closures) that allows the persistent internal vars to exist as non-accessible entities only with more code.

In JS a function constructor follows the same rules of scope as a fired function. Scope and closure is set at point of definition. The reason the internal var from a function constructor lives on is because the instance with methods defined inside the same constructor referencing that var lives on.

The only thing that changes is that you've eliminated the use of prototyped methods on the constructor and have to jury-rig your own inheritance mechanism for inherited methods.

其他推荐答案

Huge JavaScript projects out there are getting built use module patterns, perhaps you have your own idea and want to make sure your code is easily readable and well structured. by learn a couple of patterns you could make your apps easier to build and to maintain. these patterns are used by the most JavaScript talented developers, for instance the folks build node js, JQuery, bootstrap, angular and others. Simple Example:

  function foo (){
    console.log("foobar");
};

foo();

when we invoke this simple method, we will notice it’s accessible in global name space, and when we talking about large application this is a huge problem.

this is sometimes we refer to it as cluttering the global name space. The reason this is a problem is because so much is happening in the browser, you might load angular, bootstrap and Jquery in the browser, you might even have a few other javascript libraries. Now if you have to navigate a bunch of variables that clutter the global name space, it could be quit a no sense. In fact it could be even a catastrophic if the variables you create share the same name as variables from another library. The most basic module pattern is going to solve this. To do this I describe my code in a self executing anonymous function, and now looks like this: From this:

function foo (){
    console.log("foobar");
};

foo();

To this:

(function(){function foo (){
    console.log("foobar");
};

foo();
}());

we wrap a function enclosure () and then I can call it, the reason in need to wrap the function enclosure is because the function itself without a name will return undefined, however when we wrap the function parenthesis we are essentially saying treat this whole thing as an expression which is evaluated immediately and doesn’t necessarily require a naming or assignment, now when we run the code and check the browser we will see that now the global namespace isn’t clutter with my variable. We could see that foo is undefined.

source treehouse workshop about basics module pattern in JavaScript