Skip to content

Commit d849150

Browse files
Describe how we can build modules in javascript.
We can not only utilize functions/closures for re-use, but also for scoping and namespacing.
1 parent 492f3dc commit d849150

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

modules.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Javascript functions let you create modules
2+
// which help prevent naming conflicts
3+
4+
// Define a function which instantiates an object, its public and
5+
// private methods, and immediately execute it (it returns the object)
6+
NAMESPACE.module = (function () {
7+
var privateVariable;
8+
9+
function privateFunction(x) {
10+
// do something with x and privateVariable
11+
}
12+
13+
return {
14+
// public functions!
15+
firstMethod: function (a, b) {
16+
// privateVariable has scope here, not just a & b
17+
},
18+
19+
secondMethod: function (c) {
20+
// you can call privateFunction here as well
21+
}
22+
};
23+
}());
24+
25+
26+
// Or, a variation on the above could look like this:
27+
(function() {
28+
var privateVariable;
29+
30+
function privateFunction(x) {
31+
// do something with x and privateVariable
32+
}
33+
34+
GLOBAL.firstMethod = function (a, b) {
35+
// privateVariable has scope here, not just a & b
36+
};
37+
38+
GLOBAL.secondMethod = function (c) {
39+
// you can call privateFunction here as well
40+
};
41+
}());
42+
43+
// Please note that in this second example, the outermost parentheses
44+
// are REQUIRED in order for it to be a function expression and not just
45+
// a function statement.

0 commit comments

Comments
 (0)