Understanding the Module Pattern in JavaScript

Of all the design patterns you are likely to encounter in JavaScript, the module pattern is probably the most pervasive遍布的,充斥各处的. But it can also look a little strange to developers coming from other languages.

Let's walk through an example to see how it works. Suppose that we have a library of utility functions that looks something like this:

var batman = {
identity: "Bruce Wayne", fightCrime: function () {
console.log("Cleaning up Gotham.");
}, goCivilian: function () {
console.log("Attend social events as " + this.identity);
}
};

This version of batman is perfectly serviceable. It can fight crime when you call upon it. However, it has a serious weakness. This batman's identity property is publicly accessible.

Any code in your application could potentially overwrite it and cause batman to malfunction. For example:

// Some joker put this in your codebase
batman.identity = "a raving lunatic"; // Outputs: "Attend social events as a raving lunatic"
batman.goCivilian();

To avoid these sorts of situations we need a way to keep certain pieces of data private. Fortunately, JavaScript gives us just such a tool. We've even talked about it before: the immediately invoked function expression (IIFE).

A standard IIFE looks like this:

(function () {
// Code goes here
})();

The advantage of the IIFE is that any vars declared inside it are inaccessible to the outside world. So how does that help us? The key is that an IIFE can have a return value just like any other function.

var batman = (function () {
var identity = "Bruce Wayne"; return {
fightCrime: function () {
console.log("Cleaning up Gotham.");
}, goCivilian: function () {
console.log("Attend social events as " + identity);
}
};
})();
// Outputs: undefined
console.log(batman.identity); // Outputs: "Attend social events as Bruce Wayne"
batman.goCivilian();

As you can see, we were able to use the IFFE's return value to make batman's utility functions publicly accessible. And at the same time we were able to ensure that batman's identityremains a secret from any clowns who want to mess with it.

You might be wondering when using the module pattern is a good idea. The answer is that it works well for situations like the one illustrated here. If you need to both enforce privacy for some of your data and provide a public interface, then the module pattern is probably a good fit.

It is worth considering, though whether you really need to enforce data privacy, or whether using a naming convention to indicate private data is a better approach. The answer to that question will vary on a case by case basis. But now you're equipped to enforce data privacy if necessary.

Thanks for reading!

Josh Clanton

扩展阅读

Javascript中的Module(模块)模式

Understanding the Module Pattern in JavaScript的更多相关文章

  1. JavaScript Module Pattern: In-Depth

    2010-03-12 JavaScript Module Pattern: In-Depth The module pattern is a common JavaScript coding patt ...

  2. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  3. Learning JavaScript Design Patterns The Module Pattern

    The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...

  4. JavaScript module pattern精髓

    JavaScript module pattern精髓 avaScript module pattern是一种常见的javascript编码模式.这种模式本身很好理解,但是有很多高级用法还没有得到大家 ...

  5. 玩转JavaScript module pattern精髓

    JavaScript module pattern是一种常见的javascript编码模式.这种模式本身很好理解,但是有很多高级用法还没有得到大家的注意.本文,我们将回顾这种设计模式,并且介绍一些高级 ...

  6. Publish/Subscribe Pattern & Vanilla JavaScript

    Publish/Subscribe Pattern & Vanilla JavaScript https://en.wikipedia.org/wiki/Publish–subscribe_p ...

  7. JavaScript基础对象创建模式之模块模式(Module Pattern)(025)

    模块模式可以提供软件架构,为不断增长的代码提供组织形式.JavaScript没有提供package的语言表示,但我们可以通过模块模式来分解并组织 代码块,这些黑盒的代码块内的功能可以根据不断变化的软件 ...

  8. Javascript Module pattern template. Shows a class with a constructor and public/private methods/properties. Also shows compatibility with CommonJS(eg Node.JS) and AMD (eg requireJS) as well as in a br

    /** * Created with JetBrains PhpStorm. * User: scotty * Date: 28/08/2013 * Time: 19:39 */ ;(function ...

  9. 对象创建模式之模块模式(Module Pattern)

    模块模式可以提供软件架构,为不断增长的代码提供组织形式.JavaScript没有提供package的语言表示,但我们可以通过模块模式来分解并组织代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需 ...

随机推荐

  1. Python3 AES加解密(AES/ECB/PKCS5Padding)

    class AesEncry(object): key = "wwwwwwwwwwwwwwww" # aes秘钥 def encrypt(self, data): data = j ...

  2. Object.create()的使用方法

    Object.create()的使用方法:https://blog.csdn.net/wang252949/article/details/79109437

  3. 打印页面内容,<input>不好使,用<textarea> 代替

    <textarea class="sld-textarea" onchange="changeTextareaValue(this)">123< ...

  4. PHP支付宝手机网站支付功能

    1.开通支付宝商家中心里面的手机网站支付 2.再去开放平台-开发者中心-创建移动支付的应用-获取到APPID 3.接着去文档中心下载DEMO 其实demo很简单.如果第一次看的话会存在看不懂的状态. ...

  5. vue中使用better-scroll滚动条插件

    应用场景: overflow: hidden会让超出的部分隐藏,并且无法拖拽,所以可使用插件让长列表限定的区域滚动拖拽. 参考:https://zhuanlan.zhihu.com/p/2740702 ...

  6. java中构造器(Constructor)

    大部分内容转自:http://tech.it168.com/j/2006-05-18/200605181021879.shtml        构造器是一个创建对象时被自动调用的特殊方法,为的是初始化 ...

  7. 基于maven搭建hibernate运行环境

    准备案例需要的数据库表和测试数据 建表语句: create table DEPARTMENT ( DEPT_ID integer not null, DEPT_NAME ) not null, DEP ...

  8. /etc/nscd.conf - 域名服务缓存守护进程配置文件

    描述 DESCRIPTION 该文件 /etc/nscd.conf 在启动 nscd(8) 时读入.每一行或者指定一个属性和值,或者指定一个属性.服务和一个值.域之间通过空格或者TAB分开.‘#’表示 ...

  9. tortoise svn回滚常用命令

    一.revert to this version 和 revert changes from this version的区别 假设SVN已有版本4814-4854:1.基于4837版本执行[rever ...

  10. 001-supervisor

    supervisor 使用教程(转) 原文地址:https://word.gw1770df.cc/2016-08-04/linux/supervisor-%E4%BD%BF%E7%94%A8%E6%9 ...