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 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
扩展阅读
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的语言表示,但我们可以通过模块模式来分解并组织代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需 ...
随机推荐
- 部署CM集群首次运行报错:Formatting the name directories of the current NameNode.
1. 报错提示 Formatting the name directories of the current NameNode. If the name directories are not emp ...
- Spark-Core RDD行动算子
1.reduce(func) 通过func函数聚集RDD 中的所有元素,先聚合分区内数据,再聚合分区间数据. scala> val rdd1 = sc.parallelize(1 to 100) ...
- ubuntu14 文件夹添加/删除书签
1. 打开文件管理,进入你要添加书签的目录 2. 把鼠标移到顶部选择“Bookmarks" 3. 这是文件管理左侧可以看到 4. 右键可以选择删除
- 解决ie低版本不认识html5标签
在不支持HTML5新标签的浏览器里,会将这些新的标签解析成行内元素(inline)对待,所以我们只需要将其转换成块元素(block)即可使用,但是在IE9版本以下,并不能正常解析这些新标签,但是却可以 ...
- 洛谷P3412 仓鼠找$Sugar\ II$题解(期望+统计论?)
洛谷P3412 仓鼠找\(Sugar\ II\)题解(期望+统计论?) 标签:题解 阅读体验:https://zybuluo.com/Junlier/note/1327573 原题链接:洛谷P3412 ...
- go & AI核心代码
- <img> 标签的 src 属性
src属性 加载的时候就会请求 1.servlet生成一个图片 2.你直接输入servlet的连接看一下,就是一个图片,和我们自己发布到服务器的一样. 3.页面加载时,会访问这个servelt连接,自 ...
- layoutSubviews何时调用的问题(原文:http://www.cnblogs.com/pengyingh/articles/2417211.html)
今天跟旺才兄学习了一下UIView的setNeedsDisplay和setNeedsLayout方法.首先两个方法都是异步执行的.而setNeedsDisplay会调用自动调用drawRect方法,这 ...
- JAVA中关于日期的最常见的操作
//获取当前系统的时间戳 long times = System.currentTimeMillis(); //创建一个当前日期对象 Date now = new Date(); //基于指定的时间戳 ...
- php 多维数组转一维数组
1.巧用 RecursiveIteratorIterator $k_arrays_arrays_tmp = iterator_to_array(new RecursiveIteratorIterato ...