JavaScript 模块是最常用的设计模式,用于保持特定的代码独立于其他组件。
对于那些熟悉面向对象的语言的人来说,模块是JavaScript的类
。类的许多优势之一是 encapsulation - 保护状态和行为免受来自其他类的访问。
模块应该是即时调用函数表达式(IIFE),以允许私有范围 - 即保护变量和方法的关闭(然而,它会返回一个对象而不是一个函数)。
1(function() {
2
3 // declare private variables and/or functions
4
5 return {
6 // declare public variables and/or functions
7 }
8
9})();
在这里,我们在返回我们想要返回的对象之前实例化了私有变量和/或函数。我们关闭的代码无法访问这些私有变量,因为它不在相同的范围内。
1var HTMLChanger = (function() {
2 var contents = 'contents'
3
4 var changeHTML = function() {
5 var element = document.getElementById('attribute-to-change');
6 element.innerHTML = contents;
7 }
8
9 return {
10 callChangeHTML: function() {
11 changeHTML();
12 console.log(contents);
13 }
14 };
15
16})();
17
18HTMLChanger.callChangeHTML(); // Outputs: 'contents'
19console.log(HTMLChanger.contents); // undefined
请注意,callChangeHTML
与返回的对象结合,并且可以在HTMLChanger
名称空间中引用。
显示模块模式
模块模式的变异被称为启示模块模式
(Revealing Module Pattern)(Revealing Module Pattern)(Revealing Module Pattern)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Revealing Module)(Re
1var Exposer = (function() {
2 var privateVariable = 10;
3
4 var privateMethod = function() {
5 console.log('Inside a private method!');
6 privateVariable++;
7 }
8
9 var methodToExpose = function() {
10 console.log('This is a method I want to expose!');
11 }
12
13 var otherMethodIWantToExpose = function() {
14 privateMethod();
15 }
16
17 return {
18 first: methodToExpose,
19 second: otherMethodIWantToExpose
20 };
21})();
22
23Exposer.first(); // Output: This is a method I want to expose!
24Exposer.second(); // Output: Inside a private method!
25Exposer.methodToExpose; // undefined
虽然这看起来更干净,但显而易见的缺点是无法参考私人方法,这可能带来单位测试的挑战。