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. Java中的四种权限修饰符

    权限修饰符   public protected [default] private 同一个类 YES YES YES YES 同一个包 YES YES YES NO 不同包子类 YES YES NO ...

  2. 通过编写串口助手工具学习MFC过程——(五)添加CheckBox复选框

    通过编写串口助手工具学习MFC过程 因为以前也做过几次MFC的编程,每次都是项目完成时,MFC基本操作清楚了,但是过好长时间不再接触MFC的项目,再次做MFC的项目时,又要从头开始熟悉.这次通过做一个 ...

  3. getchar、putchar、puts、gets

    getchar(字符)  输入获取一个字符 putchar(字符)  输出控制台一个字符 scanf()格式化输入 printf() 格式化输出 gets(arr) 输入一个字符串给已经声明的数组ar ...

  4. WordPress用户的权限类

    WordPress的权限类这是管理 WordPress 用户权限最常用的函数.WordPress 用于角色和权限幕后工作的三个类,以及这些类提供的接口,我们可以在插件中进行高级权限管理.这三个类是: ...

  5. git error: failed to push some refs to 'git@github.com:xxx/xxx.git'

    本地仓库中和远程仓库不一致,缺少readme.md文件 解决方式参见:https://blog.csdn.net/qq_37281252/article/details/79044798

  6. k3 cloud付款单提示余额不足,科目余额表中余额为正,银行存款流水账中未负数

    对比科目余额表中的科目明细账和银行存款流水账,发现科目余额表不全,这说明有部分凭证没做,付款的时候验证的主要以银行流水账为主(主要来自现金流量表),这时候需要调整出纳部分和总账部分

  7. UIDynamic物理引擎

    iOS开发拓展篇—UIDynamic(简单介绍) 一.简单介绍 1.什么是UIDynamic UIDynamic是从iOS 7开始引入的一种新技术,隶属于UIKit框架 可以认为是一种物理引擎,能模拟 ...

  8. Django框架简易图

  9. 2019-11-28-win10-uwp-提示-Cannot-find-a-Resource-with-the-Name-Key-找不到资源

    title author date CreateTime categories win10 uwp 提示 Cannot find a Resource with the Name Key 找不到资源 ...

  10. JavaScript设计模式样例四 —— 单例模式

    单例模式(Singleton Pattern): 定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点. 目的:阻止其他对象实例化其自己的单例对象的副本,从而确保所有对象都访问唯一实例. 场景: ...