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:
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 || {};
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With