Monday, April 16, 2012

Javascript static method in class defined inside global object

I know Javascript doesn't have classes in the same way that traditional OOP languages do and that a "class" definition such as the following, is merely a function object that can be used with the new keyword:



function MyClass(){
this.a = function(){ /* Do something */ }; // Public function
function b(){ /* Do something */ }; // Private function
}


What I'm wondering is, if I define a global object (to avoid polluting the namespace) and define my classes inside this object, can I define a static method for my class in a nicer way than this:



var MyObject = {
MyClass: function(){
this.a = function(){ /* Do something */ }; // Public function
function b(){ /* Do something */ }; // Private function
},
}
MyObject.MyClass.MyStaticMethod = function(){ /* Do something */ };


I was thinking something along the lines of defining MyStaticMethod inside the MyClass function scope - is this possible?





No comments:

Post a Comment