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.
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:
http://jsfiddle.net/dbrecht/EQ4Tb/
A little off topic, but this is a little strange to me:
Why not just use:
var MyNamespace = MyNamespace || {};?