Snook on Private Methods

Tuesday, June 19th, 2007 @ 8:13 am | filed under: Code Snippets, Examples, Organizing Code

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:

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.

Comments are closed.