I'm certainly no expert, but since I've been been doing a bit of research on OOP in JavaScript lately, I thought I'd weigh in. Looking forward to seeing what other people have to say!
> when you should do object instantiation (i.e.: new Foo();) vs just creating a singleton? I think it depends a lot on what your object does. If it's a non-UI object, there's a good chance you'll want it more than once . . . and if you want it more than once, you obviously don't use a singleton. If you only need one, or if only one makes sense, use a singleton. That's probably all obvious. Where it gets confusing, at least for me, it when it comes to objects that have UI counterparts in the DOM (widgets, some call them). Most widgets are small things, like a tooltip or an auto-completing textbox. It's very possible that you'll want more than one of these on the page at a time, so I make these as instantiable (a word?) objects. This way, they're also easier to inherit from: you can create a different widget by inheriting and making small changes. This makes the code much easier to maintain. A singleton with UI probably makes more sense as being the app itself, controlling all the widgets. > Or how to organize your API in a manner which makes code reusable, readable and > maintainable. Anyone know of any good resource for this? The inheritable widgets are pretty reusable and maintainable, if you use them correctly. The way I currently find the cleanest to do this is via `Object.create`. I create an object literal as my prototype, then use `Object.create` to create instances. The great thing about `Object.create` is that you can wrap this behaviour (and even the prototype object) in a function to make it most easy to customize. Another great thing is that you can use `Object.create` on an instance and then customize it to make a sorta-singleton. Here's a pretty basic example: https://gist.github.com/737791 You've probably already seen this, but Aaron Newton has a great talk on "Programming to Patterns" at JSConf: http://jsconf.blip.tv/file/3825733/. That talk is part of what got me interested in OOP in JS. Also, Doug Crockford talks about his idea of "power constructors" in his talk "Function the Ultimate"; http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-3 ; that's pretty neat, too. I don't know if any of this is helpful. I'll be interested in what everyone else has to say.
_______________________________________________ JSMentors mailing list [email protected] http://jsmentors.com/mailman/listinfo/jsmentors_jsmentors.com List Archive: http://jsmentors.com/pipermail/jsmentors_jsmentors.com/
