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

扩展阅读

Javascript中的Module(模块)模式

原文地址:https://www.cnblogs.com/chucklu/p/11094576.html

时间: 2024-08-27 21:14:17

Understanding the Module Pattern in JavaScript的相关文章

JavaScript Patterns 5.4 Module Pattern

MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties array_string = "[object Array]", ops = Object.prototype.toStr

JavaScript Module Pattern: In-Depth

The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advance

转载翻译文章:JavaScript Module Pattern: In-Dept

# JavaScript Module Pattern: In-Depth # 转载翻译文章:JavaScript Module Pattern: In-Depth*原文*:http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html 模块模式是一种常见的js开发编码模式.通常来说,它很好理解,但还有一些高级应用并没有得到太多关注.这篇文章,我将回顾基础知识,并介绍一些真正了不起的高级主题,其中包括一个我认为极为原始的

Learning JavaScript Design Patterns The Module Pattern

The Module Pattern Modules Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized. In JavaScript, there are several options for impleme

JavaScript基础对象创建模式之模块模式(Module Pattern)(025)

模块模式可以提供软件架构,为不断增长的代码提供组织形式.JavaScript没有提供package的语言表示,但我们可以通过模块模式来分解并组织 代码块,这些黑盒的代码块内的功能可以根据不断变化的软件需求而不断的被添加,替代和删除.模块模式由几种我们已经介绍过的模式共同组成: 命名空间模式 即时函数模式 私有成员与访问控制方法模式 依赖声明模式 模块模式的第一步是建立一个命名空间.首先我们用先前介绍的namespace()方法创建一个工具模块例子,这个例子模块提供一些数组功能: MYAPP.na

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(global){ "use strict"; var M = function() { // Constructor. arguments are passed // from Module() call. this refers to m. function init() { meth

递归、闭包、私有变量、特权方法、单例、模块模式(module pattern)

//使用命名函数表达式实现递归 var factorial = (function f(num) {     if (num <= 1) {         return 1;     } else {         return num * f(num - 1);     } }); //用作块级作用域(私有作用域)的匿名函数 (function(){     var now = new Date();     if (now.getMonth() == 0 && now.get

26个精选的JavaScript面试问题

为了保证可读性,本文采用意译而非直译.另外,本文版权归原作者所有,翻译仅用于学习. 根据Stack Overflow 2018年年度调查报告,JavaScript已经连续6年保持最常用的编程语言的记录.对于一个全栈工程师,JavaScript可以说是一项必备语言,在面试中总会被问到.我整理了一下FullStack.Cafe上所有常见的JavaScript面试问题供大家参考: Q1: JavaScript中类型转换是怎样的?话题: JavaScript难度: 0在JavaScript中,在两个不同

Javascript Module 模式

Javascript Module Pattern 可以说是在Javascript代码实现过程中的最佳实践方法,能够清晰地表达Javascript面向对象的概念.其核心理念是用Javascript的“类”封装私有和公有的属性和方法.它不允许开发人员定义全局变量去“污染”全局对象.通过这种模式,可以提高Web的性能,也利于维护Javascript的代码. 在Javascript程序设计语言中,函数可以作为一个模块,在某些情况下,需要创建的是单例对象,而不是创建一个类的实例.在模块的内部,公共接口可