Many many different ways for doing similar things. Let's see if I remember how ...
1) Create object with dynamically added members, and
prototypal inheritance from that object:
-
http://pastie.org/2661313
2) Create object with function constructor, and
parasitic inheritance from that object:
-
http://pastie.org/2661334
3) Create object with object literals, and
prototypal inheritance from that object:
-
http://pastie.org/2661348
4) Create object with prototype, and
pseudoclassical inheritance from that object:
-
http://pastie.org/2681962
5) Create object with
Powerconstructor pattern (a.k.a. module pattern), and
parasitic inheritance from that object:
-
http://pastie.org/2661396
Personally I find the syntax of 1), 3) and 4) unnecessarily complicated and tricky.
I like the syntax of 2) and easy to remember, it has two drawback
- it hides how really objects and inheritance work in Javascript (there are no classes instead objects are created dynamically at run-time and objects inherit from other objects used as a prototype; adding members at run-time to a prototype add the members automatically to all the objects that inherit from it)
- Requires the new operator; if new is omitted by mistake then object members are added to the global object that get clobbered. No warning or run-time error when this happens. And it is the source of serious security flaws and tricky bugs
I find the 5) quite clean and easy to remember. It permit to avoid the use of new operator and the risks when omitting it by mistake. And the syntax follow the way object creation and inheritance work in Javascript.
I was inspired to try these exercises by the presentations from Douglas Crockford:
JavaScript: The Good Parts and
Advanced JavaScript.