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
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