Which is better pattern for javascript class

K

ksachdeva

Hi,

Here are 2 common patterns that I see when creating modular / object
oriented javascript.

Pattern 1:

var MyJSUtil = function(){

var _var1;
var _var2;

return {
init : function(){
alert(_var1); // _var1 and _var2 are accessible from this
method
},

dispose : function(){
}

};
}();

// call init method of MyJSUtil
MyJSUtil.init();

Pattern 2:
MyJSUtil = {
this._var1 = 0;
this._var2 = 0; // these are _public_ instance variables and not
local or private [but I really want private]
};

MyJSUtil.prototype = {

init : function() {
alert(this._var1);
},

dispose : function(){
alert(this._var2);
}

};


---------------

One benefits of pattern1 that I see is that you can have a notion of
private variables for your public methods.

Would appreciate if some javascript guru can explain which is a better
way of writitng javascript modular components/classes and why. May be
both are to be used depending on requirements so my question would be
what would be those situations.

Regards & thanks
Kapil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top