How to set up JavaScript namespace and classes properly?
Do neither of those things.
Make a javascript "class":
var MyClass = function () { var privateVar; //private var privateFn = function(){}; //private this.someProperty = 5; //public this.anotherProperty = false; //public this.someFunction = function () { //public //do something };};MyNamespace.MyClass = new MyClass();
One with static vars:
var MyClass = (function(){ var static_var; //static private var var MyClass = function () { var privateVar; //private var privateFn = function(){}; //private this.someProperty = 5; //public this.anotherProperty = false; //public this.someFunction = function () { //public //do something }; }; return MyClass;})();MyNamespace.MyClass = new MyClass();
With a "constructor" (all of the examples have a "constructor", this one just has parameters to work with):
var MyClass = function (a, b c) { //DO SOMETHING WITH a, b, c <-- var privateVar; //private var privateFn = function(){}; //private this.someProperty = 5; //public this.anotherProperty = false; //public this.someFunction = function () { //public //do something };};MyNamespace.MyClass = new MyClass(1, 3, 4);
With all of the above you can do:
MyNamespace.MyClass.someFunction();
But you cannot do (from the outside):
MyNamespace.MyClass.privateFn(); //ERROR!
The first example is simply an Object literal - it cannot be instantiated and doesn't have private members. The second example has some incorrect syntax (var someProperty: 5
should be var someProperty = 5
) but is using a closure to encapsulate internal private state within a self-invoking anonymous function.
The second approach looks better for encapsulating private members, but could be made more "Object-oriented" by making it an instantiable class:
MyNamespace.MyClass = function() { ... };MyNamespace.MyClass.prototype.someProperty = 'foo';
Then you can instantiate it with the 'new' keyword:
var aClass = new MyNamespace.MyClass();aClass.init(...);
I use the following syntax for the instantiable classes with namespace
var MYNamespace = MYNamespace|| {}; MYNamespace.MyFirstClass = function (val) { this.value = val; this.getValue = function(){ return this.value; }; }var myFirstInstance = new MYNamespace.MyFirstClass(46);alert(myFirstInstance.getValue());
jsfiddle: http://jsfiddle.net/rpaul/4dngxwb3/1/