Friday, September 20, 2013

Hiding Privates (Part 2)

In a follow up to my earlier post about not using an underscore to indicate privacy, there is a situation when dealing with instance variables on prototypes that can get a little uglier. However, hiding these are also possible. Take this example.

function UserView(userRepo, console) {
 this.userRepo = userRepo;
 this.console = console;
}

UserView.prototype = {
 render: function () {
  var model;
  
  this.console.log("Rendering UserView");
  model = this.userRepo.getUsers();
  //…
 }
};
Let's say that for whatever reason the userRepo and console objects should not be exposed. Anyone with access to the UserView could then use these directly to do some logging and access the repo without going through dependency injection or whatever module system you have setup. So how do you hide these variables? Glad you're curious. One way is to store them in an object.
(function () {
 
 var privates = {},
     cid = 0;
 
 function UserView(userRepo, console) {
  this.cid = cid++;
  privates[cid] = {
   userRepo: userRepo,
   console: console
  };
 }
 
 UserView.prototype = {
  render: function () {
   var model,
        _ = privates[this.cid];
   
   _.console.log("Rendering UserView");
   model = _.userRepo.getUsers();
   //…
  },
  close: function () {
   delete privates[this.cid];
  }
 };
 
}());
The ugly part of this (besides the photo at the top), is that you need to remember to delete your privates. Don't worry, it won't hurt.

No comments:

Post a Comment