Javascrip: objects creation and inheritance

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:

2) Create object with function constructor, and parasitic inheritance from that object:

3) Create object with object literals, and prototypal inheritance from that object:

4) Create object with prototype, and pseudoclassical inheritance from that object:

5) Create object with Powerconstructor pattern (a.k.a. module pattern), and parasitic inheritance from that object:

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
  1. 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)

  2. 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.

Print | posted @ Saturday, October 8, 2011 7:21 PM

Comments on this entry:

Gravatar # re: Javascrip: objects creation and inheritance
by Abx78 at 10/19/2011 3:34 PM

On the 5th there is no inheritance at all. You just recreate an object and add a method on it.

I personally prefer the 3rd but the way it's written is useless.

4th is cool but such a mental one... :D
Gravatar # re: Javascrip: objects creation and inheritance
by Luca Minudel at 10/19/2011 3:48 PM

Hi Abx78,

de gustibus non est disputandum :D

guess it's interesting to note that languages that have only objects and not classes (as javascript) do inheritance adding methods to the base objects. As you noted for the 5th.

P.S. thanks for your feedback

Your comment:

Italic Underline Blockquote Hyperlink
Please add 6 and 5 and type the answer here: