Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up JavaScript namespace and classes properly?

It seems there are so many ways to set up a JavaScript application so it is confusing as to which one is correct or best. Are there any difference to the below techniques or a better way of doing this?

MyNamespace.MyClass = {
    someProperty: 5,
    anotherProperty: false,

    init: function () {
        //do initialization
    },

    someFunction: function () {
        //do something
    }
};

$(function () {
    MyNamespace.MyClass.init();
});

Another way:

MyNamespace.MyClass = (function () {
    var someProperty = 5;
    var anotherProperty = false;

    var init = function () {
        //do something
    };

    var someFunction = function () {
        //do something
    };

    return {
        someProperty: someProperty
        anotherProperty: anotherProperty
        init: init
        someFunction: someFunction
    };
}());

MyNamespace.MyClass.init();

The first technique feels more like a class. I am coming from server-side background if this makes a difference. The second technique seems more redundant and a bit awkward, but I see this used a lot too. Can someone please help shed some light and advise the best way to move forward? I want to create a application with lots of classes talking to each other.

like image 669
TruMan1 Avatar asked Jul 25 '12 14:07

TruMan1


People also ask

How does namespace work in JavaScript?

Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

How classes are implemented in JavaScript?

The process of natively implementing classes is what we call a syntax sugar. This is just a fancy syntax that compiles down to the same primitives that are already supported in the language. You can use the new easy-to-use class definition, but it will still lead to creating constructors and assigning prototypes.

Is namespace a class?

The namespace and classes are two different concepts. Classes are datatypes. Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one.


3 Answers

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!
like image 84
Naftali Avatar answered Oct 16 '22 22:10

Naftali


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(...);
like image 6
chrisfrancis27 Avatar answered Oct 16 '22 21:10

chrisfrancis27


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/

like image 4
Razan Paul Avatar answered Oct 16 '22 21:10

Razan Paul