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的语言表示,但我们可以通过模块模式来分解并组织代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需 ...
随机推荐
- Zend Framework MVC的结构
The Zend Framework MVC Architecture 一.概述: In this chapter, we will cover the following topics:1. Zen ...
- oracle 实现mysql find_set_in函数
create or replace FUNCTION F_FIND_IN_SET(piv_str1 varchar2, piv_str2 varchar2, p_sep varchar2 := ',' ...
- Vue环境搭建和项目创建
目录 vue项目 环境搭建 项目创建 vue项目 环境搭建 node node ~~ python:node是用c++编写用来运行js代码的 npm(cnpm) ~~ pip:npm是一个终端应用商城 ...
- nologin - 阻止非root用户登录系统
描述 DESCRIPTION 如果存在文件 /etc/nologin, login(1) 将只允许root访问.其它用户的登录会遭到拒绝并且显示该文件中的内容给他们. 文件 FILES /etc/no ...
- Mysql where in (几百或几千个id)的优化
1. SELECT employees.* FROM employees, clients WHERE employees.client_id = clients.id AND clients.nam ...
- Django【第7篇】:Django之ORM跨表操作(聚合查询,分组查询,F和Q查询等)
django之跨表查询及添加记录 一:创建表 书籍模型: 书籍有书名和出版日期,一本书可能会有多个作者,一个作者也可以写多本书,所以作者和书籍的关系就是多对多的关联关系(many-to-many); ...
- 微信小程序 背景音频播放遇到的深坑
1.微信前台(聊天页)暂停后回到小程序,再点击播放,播放信息消失,无法续播 ios可以监听到 (onStop已经停止)事件, 安卓无法监听到,只能监听到普通的暂停事件. 2.
- Java验证码程序
1.设计思想利用random的随机生成数字,利用for循环控制随机数字的个数来控制验证码的输出.利用JFrame实现布局的管理,对登录框内容的位置进行管理. 2.流程图 3.源代码 denglu类 i ...
- MongoDB的$作为下标的用法
在MongoDB中有一个非常神奇的符号 "$" "$" 在 update 中 加上关键字 就 变成了 修改器 其实 "$" 字符 独立出现 ...
- pyqt5-QAbstractScrollArea滚动条
继承 QObject-->QWidget-->QFrame-->QAbstractScrollArea 是抽象类 import sys from PyQt5.QtWidgets i ...