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的语言表示,但我们可以通过模块模式来分解并组织代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需 ...
随机推荐
- 循环Gray码的生成(非递归)
#!/usr/bin/env python #coding:utf-8 import sys def gray_code(n): if n < 1: return [] n += 1 array ...
- 字符串中的replace方法
String.prototype.replace() 该方法作为字符串中非常常用的方法, 今天我们具体介绍一下它的用法 语法格式 someString.replace(regxp | substr, ...
- tableview(model base)
该tableview控件的用法: 1.原理: 数据存放在“表”对象中,而将这个对象关联到tableview控件之后,将实现在UI中展示出来. class Query_Students : public ...
- 4G 内存怎么读取一个 5G 的数据?
方法一:可以通过生成器,分多次读取,每次读取数量相对少的数据(比如 500MB)进行处理,处理结束后在读取后面的 500MB 的数据. 方法二:可以通过 linux 命令 split 切割成小文件,然 ...
- HDU - 1845 Jimmy’s Assignment (二分匹配)
Description Jimmy is studying Advanced Graph Algorithms at his university. His most recent assignmen ...
- 检验Excel中数据是否与数据库中数据重复
#region 记录Excel中的重复列 /// <summary> /// 记录Excel中的重复列 /// </summary> /// <param name=&q ...
- Aniamtion加载动画
css新增样式Animation的运用 希望可以通过这个案例加深对Animation以及Transform 两大api的认识 效果图如下: 在这里需要注意的是:理应通过发送服务器请求来获取图片,从而达 ...
- 看完阮一峰的React教程后, 我写了一个TodoList
看完阮一峰的React教程后,就自己做了这个TodoList,自己慢慢琢磨效率差了点但是作为入门小练习还是不错的. 以下是效果图:我的源码:todolistUI:bootstrap 4 一.组件化 我 ...
- Docker守护式容器的创建和登录
创建守护式容器 如果对于一个需要长期运行的容器来说,我们可以创建一个守护式容器(后台运行的容器). 创建(-d)并运行(-i)守护式容器命令如下(容器名称不能重复): docker run -id - ...
- mailstats - 显示邮件状态信息
总览 mailstats [-o] [-C cffile] [-f stfile] 描述 mailstats工具显示当前的邮件状态信息. 首先,先显示统计启动时所记录的时间,当然是以ctime(3)所 ...