0

If my site doesn't require any sort of optimization and my object structure is fairly flat and so there is no need for inheritance, should I be using prototypes at all:

MyObject.prototype.<something>

I refer to this question Javascript when to use prototypes and various writings by John Resig who seems to focus on the performance values of prototype.

I find using the module pattern to define objects and their functions easier to read and manage and as michielvoo mentions, premature optimization tends to cause more harm than good.

Are there any other benefits or uses cases for prototype?

Community
  • 1
  • 1
rogermushroom
  • 5,486
  • 4
  • 42
  • 68
  • 1
    what about debugging and IDE support ? NetBeans can't analyze module pattern. Stack trace shows "Anonymous 45" instead of function names. – c69 Jan 18 '12 at 23:28
  • ´This is a fair point, you should create an answer with it. – rogermushroom Jan 18 '12 at 23:31

2 Answers2

1

Well, if you refer to that question, the accepted answer for which starts out by calling it an optimization, then I'd say don't go for premature optimization. You may never reap any benefits (see: YAGNI) and you make your job more difficult, since you yourself (and your team?) prefer the module pattern.

Michiel van Oosterhout
  • 22,839
  • 15
  • 90
  • 132
  • This was my point (although admittedly it wasn't very clear). I generally see no need for this sort of optimization and so I guess I shouldn't be using it. – rogermushroom Jan 18 '12 at 23:25
  • I'd say, if and when the need arises. And even then, you may still get more mileage by optimizing your module implementation. – Michiel van Oosterhout Jan 18 '12 at 23:29
  • I think the main difference is that prototypes are OO and that "modules" are functional. In reality the "module pattern" is a ugly hybrid, but it's perfectly valid to use a real functional alternative for your code organization – Raynos Jan 18 '12 at 23:36
1

It's a code organization pattern.

There are two good ways to share methods across objects

var oneWay = Object.create(bagOfMethods);
// some value of extend that is sensible
var otherWay = extend({}, bagOfMethods);

The only real advantage prototypes gives is that the link between oneWay and bagOfMethods is live.

Having a live link allows really powerful extensions and monkey patching.

An example is Object.prototype.methodNowLivesOnAllInstances = function () { };

This is a way of doing "asynchronous" programming, you can extend the "class" without worrying whether all instances get the new method.

A note on the modular pattern, it's bloated and not needed. Use a module builder like modul8 or browserify instead.

Raynos
  • 166,823
  • 56
  • 351
  • 396