Understanding the Module Pattern in JavaScript
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 var
s 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 identity
remains 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
扩展阅读
Understanding the Module Pattern in JavaScript的更多相关文章
- JavaScript Module Pattern: In-Depth
2010-03-12 JavaScript Module Pattern: In-Depth The module pattern is a common JavaScript coding patt ...
- JavaScript Patterns 5.4 Module Pattern
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...
- Learning JavaScript Design Patterns The Module Pattern
The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...
- JavaScript module pattern精髓
JavaScript module pattern精髓 avaScript module pattern是一种常见的javascript编码模式.这种模式本身很好理解,但是有很多高级用法还没有得到大家 ...
- 玩转JavaScript module pattern精髓
JavaScript module pattern是一种常见的javascript编码模式.这种模式本身很好理解,但是有很多高级用法还没有得到大家的注意.本文,我们将回顾这种设计模式,并且介绍一些高级 ...
- Publish/Subscribe Pattern & Vanilla JavaScript
Publish/Subscribe Pattern & Vanilla JavaScript https://en.wikipedia.org/wiki/Publish–subscribe_p ...
- JavaScript基础对象创建模式之模块模式(Module Pattern)(025)
模块模式可以提供软件架构,为不断增长的代码提供组织形式.JavaScript没有提供package的语言表示,但我们可以通过模块模式来分解并组织 代码块,这些黑盒的代码块内的功能可以根据不断变化的软件 ...
- 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 ...
- 对象创建模式之模块模式(Module Pattern)
模块模式可以提供软件架构,为不断增长的代码提供组织形式.JavaScript没有提供package的语言表示,但我们可以通过模块模式来分解并组织代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需 ...
随机推荐
- C++中的字符串类
1,本文分析 C++ 中的字符串,C 语言中的字符串利用的是 C 语言中的字符数组, 在 C 语言中没有真正意义上的字符串,利用了字符数组表示了字符串,最初设 计 C 语言仅仅是为了开发 Unix ...
- Codeforces 1262E Arson In Berland Forest(二维前缀和+二维差分+二分)
题意是需要求最大的扩散时间,最后输出的是一开始的火源点,那么我们比较容易想到的是二分找最大值,但是我们在这满足这样的点的时候可以发现,在当前扩散时间k下,以这个点为中心的(2k+1)2的正方形块内必 ...
- python 序列解包(解压缩)
序列解包(解压缩) 所学的解压缩 如果我们给出一个列表,我们需要一次性取出多个值,我们是不是可以用下面的方式实现呢? name_list = ['nick', 'egon', 'jason'] x = ...
- CSP2019
$CSP\space S$ 格雷码 $solution:$ 直接模拟即可. 时间复杂度 $O(n)$ . #include<iostream> #include<cstring> ...
- 深入了解RabbitMQ工作原理及简单使用
深入了解RabbitMQ工作原理及简单使用 RabbitMQ系列文章 RabbitMQ在Ubuntu上的环境搭建 深入了解RabbitMQ工作原理及简单使用 RabbitMQ交换器Exchange介绍 ...
- empty()、isset()、is_null()的区别
总结:1. 变量有二种状态: 已声明, 未声明2. 已声明的变量也有二种状态: 已赋值(初始化), 未赋值(未初始化)3. 变量可能会被赋值类型: null, 空值, 非空值 3.1: null值: ...
- [MyBatis]诡异的Invalid bound statement (not found)错误
转自:https://blog.csdn.net/z69183787/article/details/48933481 自从开始使用Maven管理项目,最近在配置MyBatis的Mapper,在Ecl ...
- 05-转置-置换-向量空间R
一.置换矩阵 一个矩阵的行或者列交换,可以借助另外一个矩阵相乘来实现 首先是行交换: $\underbrace{\left[\begin{array}{ccc}{1} & {1} & ...
- django + celery的队列,路由与弹性
#celery_app.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import ...
- 3Linux - 常用 Linux 命令的基本使用
常用 Linux 命令的基本使用 转自 目标 理解学习 Linux 终端命令的原因 常用 Linux 命令体验 01. 学习 Linux 终端命令的原因 Linux 刚面世时并没有图形界面,所有的操作 ...