Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of JavaScript anonymous function with namespaces

Tags:

javascript

Is there any benefit when writing JavaScript classes and namespaces of this...

if(typeof MyNamespace === 'undefined'){
    var MyNamespace = {};
}

(function(){
MyNamespace.MyClass = function(){
    this.property = 'foo'

    return this;
}
}());

Versus just this...

if(typeof MyNamespace === 'undefined'){
    var MyNamespace = {};
}

MyNamespace.MyClass = function(){
    this.property = 'foo'

    return this;
}

I have seen the first pattern implemented in a few libraries, and was trying to find how out if there is any added benefit unless some sort of other function was declared inside of the anonymous function in the first example.

like image 306
jcreamer898 Avatar asked Nov 17 '11 20:11

jcreamer898


1 Answers

To your question:

Yes, there is a difference (and benefit). In your first example, you can control access control (meaning using prototype-based version of public/private member variables and functions). As an example:

var m = (function() {
    var o = {};
    o.myPublicProperty = 0; // can be accessed by instantiated object's calling code

    var myPrivateProperty = 1; // can't be accessed outside of this module

    o.myPublicFunction = function() {
        myPrivateFunction();
        return myPrivateProperty;
    };

    function myPrivateFunction() {
        ++myPrivateProperty;
        ++o.myPublicProperty;
    }

    o.getMyPrivateProperty = function() {
        return myPrivateProperty;
    }

    return o;
})();

console.log(m.myPublicProperty);       // 0
console.log(m.getMyPrivateProperty()); // 1
console.log(m.myPrivateProperty);      // undefined
console.log(m.myPublicFunction());     // increments
console.log(m.myPublicProperty);       // 1
console.log(m.getMyPrivateProperty()); // 2

http://jsfiddle.net/dbrecht/EQ4Tb/

A little off topic, but this is a little strange to me:

if(typeof MyNamespace === 'undefined'){
    var MyNamespace = {};
}

Why not just use: var MyNamespace = MyNamespace || {};?

like image 132
Demian Brecht Avatar answered Nov 02 '22 20:11

Demian Brecht