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的语言表示,但我们可以通过模块模式来分解并组织代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需 ...
随机推荐
- idea 代码部分格式化
效果: 处理Idea使用ctrl+alt+L进行代码格式化时部分代码可以被忽略,不执行格式化功能(webstorm,phpstorm同理) 原因: 有时希望自己写的一些代码不被格式化,或者发现格式化后 ...
- yii日志保存机制
一.修改yii框架的配置文件(main.php) 'log' => array( 'class' => 'CLogRouter', 'routes' => array( array( ...
- [LeetCode] 140. 单词拆分 II
题目链接 : https://leetcode-cn.com/problems/word-break-ii/ 题目描述: 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符 ...
- 完整ASP.Net Excel导入
//把EXCEL文件上传到服务器并返回文件路径 private String typename(FileUpload fileloads) { str ...
- spark复习笔记(1)
使用spark实现work count ---------------------------------------------------- (1)用sc.textFile(" &quo ...
- 安装RF
pip install robotframework wxPython pip install robotframework-ride pip install --pre --upgrade robo ...
- python中的@property
@property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/getter也是需要的 class People: def __init__(sel ...
- Android相关资源
各类黑客大会资料 https://infocon.org/cons/ 各类课程.视频 https://github.com/Developer-Y/cs-video-courses#security ...
- GUI学习之二十九—QInputDialog学习总结
最后一种对话框是QInputDialog,,用来提供个输入的窗口. 一常用的静态方法 由于输入的类型不同,QInputDialog分为多种静态方法使用 #有步长调节器的整形数据,step为步长调节器的 ...
- 刷PTA这一周的感悟
在慕课上报名了浙江大学的<数据结构>这门课,主讲人陈越老师,何钦铭老师,两位老师讲的很好,课后有配套的PTA可以用来做题,练习. 最近在PTA上刷题,发现自己代码实现能力是真的差劲,一开始 ...