Encapsulation in Javascript
jonathan-jackson.net
jonathan-jackson.net
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.
"The other way it differs from the constructor pattern is that the prototype class is not instantiated. Which reduces the memory consumption of the object (among other things)."
Admittedly, there is some ambiguity because the second statement is a fragment. The way Crockford is quoted seems to support this fallacy, though.
Echoing what jashkenas said: anything you may save on a reference to the function's prototype (minimal), you lose when creating copies of each member function.
What Crockford was speaking about in his post was using "new" directly on a function definition. In that specific case, the reference to the prototype is useless, since it is blank. In the OP's "Mammal" example, the prototype reference provides key functionality that is well worth the cost.
The module pattern boils down to trying to bring the ideas of privacy from Java into JavaScript. Java has good tools (IDEs) for interacting with, debugging, and testing objects with private data and methods. JavaScript does not.
Once you build your encapsulated module, you find yourself adding extra getters and setters to provide visibility to the code you're writing or testing. Then it turns out to be very convenient to use some of those in the API you export to other modules, and you may or may not remember to remove them before deploying, so you end up losing any supposed benefit of encapsulation.
I suspect many JS developers head down this blind alley and get burned.
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.
Modules are where it's at
(it's = it is, and you're saying "Modules are where it is at")