Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I was recently browsing a open source JavaScript project. The project is a strai

ID: 647834 • Letter: I

Question

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 ?

Explanation / Answer

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote