|
|
|
|
|
by jashkenas
5395 days ago
|
|
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. |
|
"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.