

Encapsulation in Javascript - Aviwein77
http://www.jonathan-jackson.net/encapsulation-in-javascript
Thought that it was interesting and others might enjoy it as well.
======
jashkenas
Not to be hyperbolic, but the continual promotion of the "module" pattern in
JavaScript is some of the worst advice you can give.

JavaScript has prototypes for a reason -- use them. By using the "module"
pattern to build objects, you create a separate copy of every function for
every instance of every object you create. If you're just creating a handful
of objects, it's no big deal, but if you're creating a large number of
objects, it's horribly CPU and memory inefficient.

Modern JS runtimes like Chrome/V8 can create and store a million small objects
with prototypes and "new" in a couple seconds, using just a dozen or so
megabytes of RAM. Creating the same million small objects with the "module"
pattern takes minutes, uses many hundreds of megabytes of memory, and often
crashes the browser.

And that's just the pragmatics -- there are deeper semantic reasons to use
real prototypes.

~~~
rondale_sc
Yes I suppose that's true. I think it all depends on what your case is and
preference, but yes memory is an issue with the module method. Just out of
curiosity what are the best tools out there to test memory consumption of
javascript snippets? It'd be interesting to see prototype/module/whatever_else
memory usage side by side.

~~~
jashkenas
The browsers are getting better at optimizing memory use for small closures
all the time, but there's still a long way to go. Here's a screenshot of the
Chrome heap profiler for both cases:

<http://cl.ly/A5NX>

~~~
mun2mun
I have one question. How to handle private methods in prototype/module
pattern? If I declare private function in obj function declaration I can not
access it in public functions attached to the prototype of obj. This is also
true for module pattern. This problem arises when I need to add extra method
later. How to overcome this situation?

------
latchkey
CoffeeScript FTW. <https://gist.github.com/1214296>

------
primo44
"Module's are where it's at"?

Grammar much?

And don't get me started on "login with X, Y, Z". As a verb, it's "log in". YC
has it wrong also.

~~~
rondale_sc
Fixed the header "Modules are where its at" Thanks for bringing this up.

~~~
primo44
Argghh. Please correct it again, to

    
    
        Modules are where it's at
    

(it's = it is, and you're saying "Modules are where it is at")

~~~
rondale_sc
I actually fixed it correctly on the website then typed it incorrectly in my
reply to you.

