4 ms·
How to use Private Methods in JavaScript
- kbenson 13y agoSurprisingly, 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; }); } }
- AndyKelley 13y agoInteresting results. The only problem with that kind of private method is that another Cell method wouldn't be able to call it either.
- kbenson 13y agoYeah, 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.