Skip to content

Instantly share code, notes, and snippets.

@aalvarado
Created April 20, 2011 15:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalvarado/931652 to your computer and use it in GitHub Desktop.
Save aalvarado/931652 to your computer and use it in GitHub Desktop.
namespace and object encapsulation in js
/*
sources:
http://www.justatheory.com/computers/programming/javascript/emulating_namespaces.html
http://www.dustindiaz.com/namespace-your-javascript/
http://www.crockford.com/javascript/private.html
http://yuiblog.com/blog/2007/06/12/module-pattern/
http://stackoverflow.com/questions/881515/javascript-namespace-declaration
*/
if(myNameSpace === undefined) {
var myNameSpace = function(){};
}
myNameSpace.MyClass = function(param){
// private members
var private_var = 'I\'m private, so I cannot be seen from the global scope directly';
var result;
var private_method = function(){
return 'I\'m a private method';
};
return{ //public members
public_property : 'I\'m public', //public member
another_public_property : 'I\'m public', //public member
get_private_var : function(){
return private_var;
},
get_private_var_method : function(){
return private_method(); //return the result from private_method
},
get_public_property: function(){
return this.public_property;
},
add_numbers: function(arg1, arg2){
result = arg1 + arg2;
return;
},
get_result:function(){
return result;
}
};
};
$(document).ready(function(){
var iobj = new myNameSpace.MyClass();
var iobj2 = new myNameSpace.MyClass();
iobj.add_numbers(1,2);
iobj2.add_numbers(10,20);
$('#result').append('result object1 : ' + iobj.get_result() +'<br />');
$('#result').append('result object2 : ' + iobj2.get_result() +'<br />');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment