UML for javascript?

abernier picture abernier · Jan 18, 2012 · Viewed 10.1k times · Source

I'm looking for a way of graphically representing javascript objects...

I know there is UML, but for example, how to represent the chain between 2 objects, eg:

var a, b;

a = {};
b = Object.create(a);

Intuitively, I'd draw something like this:

+-----+
|b    |
|-----|
|     |
+--+--+
   |     +-----+
   +---->|a    |
         |-----|
         |     |
         +-----+

but is there a decent representation in UML?

And what about mixins?

c = $.extend({}, a, b)

+-----+           +-----+
|a    |           |b    |
|-----|           |-----|
|     |<----------|     |
+-----+           +-----+
   +     +-----+
   |     |c    |
   |     |-----|
   +---->|     |
         +-----+

Answer

romario333 picture romario333 · Feb 23, 2012

First thing you need to know is that JavaScript uses prototype-based inheritance. This means there is no distinction between classes and instances as in other OO languages (like Java). There are just objects. One implication of that is that differentiating between class and object diagrams does not make sense.

To your first example:

var a, b;

a = {};
b = Object.create(a);

This is inheritance - object b inherits properties of object a.

Correct way to model this in UML is this class/object diagram:

object b inherits from object a

Mixins can be viewed as a form of multiple inheritance, object c is inheriting properties from object a and b, diagram for that might look like this:

object c inherits from a and b