Snook on Private Methods
Jonathan Snook has a nice write-up about using private methods in javascript.
With JavaScript, you can create private methods and properties using what Yahoo describes as the module pattern. Here's the basic construct, including a private method:
JavaScript:
MyObject = function(){var privateMethod = function(){ /* do stuff */ };
var obj = {
publicProperty:5,
publicMethod:function(){ /* do stuff */ };
};
return obj;
}(); // run it right away
If you're not familiar with this pattern, it's really quite cool. It takes advantage of closures, allowing the public methods to access the private methods. I've been using this approach in my recent work and it feels nice and works well.

Leave a Reply