Winning Arguments

So you wanted to beef up your JavaScript utility by adding a bunch of config options and now you have a constructor with 10 arguments?

Fortunately JavaScript does not support function overloading, so you only have to supply arguments up to the last non null value. Unfortunately, if you only want to provide arguments 1, 6, 7 and 10 you also need to specify a lot of null arguments in between – and you need to count the null arguments very carefully to be certain exactly which value you are assigning to which argument. And pity anyone who is trying to read your code.

function CleverThing(element, duration, rotation, suspension, gravitation, gradation, hesitation, gestation, scale, color) {
   this.element = element;
   this.duration = duration;
   this.rotation = rotation;
   ... ...

var newThing = new CleverThing('arrow', null, null, null, null, 80, 200, null, null, '#FF0000' );

Object literals to the rescue. Merge all your optional arguments into one, call it something like ‘options’, and assign attributes only as required…

Continue reading