Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  34] [ 2]  / answers: 1 / hits: 35361  / 12 Years ago, wed, july 25, 2012, 12:00:00

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.


More From » oop

 Answers
133

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!

[#84051] Monday, July 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;