Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
How to use Private Methods in JavaScript (andrewkelley.me)
2 points by AndyKelley on July 17, 2013 | hide | past | favorite | 3 comments


Surprisingly, I get much worse performance from the prototype version than the "external method" version (I wouldn't exactly call it private). Up to 50% worse in fact on Windows Chrome 28.

Interestingly, just defining initializeSomethingElse within Cell only results in ~10% slowdown, and that yields a truly private method. E.g.

    function Cell(x, y) {
      var self = this;
      self.x = x;
      self.y = y;
      self.things = [1, 2, 3];

      // private -unreachable- method
      initializeSomethingElse();

      // Private methods here
      function initializeSomethingElse() {
        self.dir = Math.atan2(self.y, self.x);
        self.total = 0;
        self.things.forEach(function(thing) {
          self.total += thing;
        });
      }
    }


Interesting results. The only problem with that kind of private method is that another Cell method wouldn't be able to call it either.


Yeah, for that you can go back to your original solution, but wrap it all in a (function(){ })() so the scope of the functions is limited to that function. I think you need to assign the Cell function to window.Cell as well to escape the scope for that one component.

Unfortunately, it was much slower when I tested it last night. Close to 60% slower compared to your original solution, or 7% - 10% slower than the original prototype method version.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: