I was recently browsing a open source
JavaScript
project. The project is a straight port from another project in C language
. It mostly use static methods, packed together in classes. Most classes are implemented using this pattern :
Foo = (function () {
var privateField = "bar";
var publicField = "bar";
function publicMethod()
{
console.log('this is public');
}
function privateMethod()
{
console.log('this is private');
}
return {
publicMethod : publicMethod,
publicField : publicField
};
})();
This was the first time I saw private methods implemented that way. I perfectly understand how it works, using a anonymous method. Here is my question : is this pattern a good practice ? What are the actual limitations or caveats ? Usually i declare my JavaScript classes like that :
Foo = new function () {
var privateField = "test";
this.publicField = "test";
this.publicMethod = function()
{
console.log('this method is public');
privateMethod();
}
function privateMethod()
{
console.log('this method is private');
}
};
Other than syntax, is there any difference with the pattern show above ?
The first form can be generalized like so:
A = (function() { return {}; })();
It gives us an object A
with no explicit constructor. The object identifies exclusively as Object
and the default Object
constructor is used. Creating another object from A
‘s constructor yields an empty object:
var a_test = new A.constructor();
a_test
will be an empty object ({}
).
The 2nd form can be generalized like so:
B = new function() { /* whatever */ }
It gives an object B
which is an instance of an anonymous function. It’s constructor is defined, and we can create new instances like so:
var b_test = new B.constructor();
In this case, b_test
will be identical to our original B
object, private members and all.
The first form prevents users from building replicas. The second form allows it.
2