Tuesday, January 3, 2012

Javascript: create a java-like static class

A static class is one you can never create a new instance of. For example, instead of having static methods in a JavaScript class, you can create a static class by declaring your functions as variables on a pure JavaScript Object. This method can be used for example for creating a class of utility functions:



var utils = {
 trim:function(str, numCharacters){
  return str.substring(0, numCharacters);
 },

 log:function(msg){
  if(console){
   console.log(msg);
  }
 }
}
var s = utils.trim("Good day to you sir", 4);
 
Source:
http://www.arpitonline.com/blog/2009/07/24/object-oriented-javascript-techniques/

No comments: