Namespaces !
by Hari Menon
HTML
<div>
<input type="button" id="submitButton" value="submit" />
</div>
JavaScript
var Spinach = {
log:function(message){
alert(message);
},
Namespace:{}
};
Spinach.Namespace.myModule = function () {
//"private" variables:
var myPrivateVar = "I can be accessed only from within Spinach.Namespace.myModule.";
//"private" method:
var myPrivateMethod = function () {
Spinach.log("I can be accessed only from within Spinach.Namespace.myModule");
};
return {
myPublicProperty: "I'm accessible as Spinach.Namespace.myModule.myPublicProperty.",
myPublicMethod: function () {
Spinach.log("I'm accessible as Spinach.Namespace.myModule.myPublicMethod.");
//Within myProject, I can access "private" vars and methods:
Spinach.log(myPrivateVar);
Spinach.log(myPrivateMethod());
//The native scope of myPublicMethod is Namespace; we can
//access public members using "this":
Spinach.log(this.myPublicProperty);
}
};
}(); // the parens here cause the anonymous function to execute and return
document.getElementById('submitButton').onclick = Spinach.Namespace.myModule.myPublicMethod;