js-closure

JS closure and something related

Closure & emulate Private Scope in JS

A closure can not only access the variables defined in its outer function but also the arguments of the outer function.

The example below creates a private scope by adding parenthesis at the end of the function, it tells the interpreter to execute it as soon as it reads it without invocation. Functions and variables in it are not accessible from outside.

1
2
3
(function () {
// private scope
})();

But what if we want some of the functions to be public?

The Module Pattern

The Module Pattern looks like this:

1
2
3
4
5
6
7
8
9
10
11
var Module = (function() {
function privateMethod() {
// do something
}
return {
publicMethod: function() {
// can call privateMethod();
}
};
})();

and can be used like this:

1
2
Module.publicMethod(); // works
Module.privateMethod(); // Uncaught ReferenceError: privateMethod is not defined

An even better way of doing this is to add underscore to the private functions and return an anonymous object containg public functions:

1
2
3
4
5
6
7
8
9
10
11
var Module = (function () {
function _privateMethod() {
// do something
}
function publicMethod() {
// do something
}
return {
publicMethod: publicMethod,
}
})();

Reference: Understanding Scope in JavaScript