Is this JS code a good way for defining class with private methods?

Posted by tigrou on Programmers See other posts from Programmers or by tigrou
Published on 2014-08-20T13:42:20Z Indexed on 2014/08/20 16:34 UTC
Read the original article Hit count: 177

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 ?

© Programmers or respective owner

Related posts about object-oriented

Related posts about JavaScript