Christian Heilmann

Posts Tagged ‘object literal’

Sending objects as parameters – good or bad?

Wednesday, November 7th, 2007

One of the differences I keep seeing in functions and methods lately is that people seem to go away from the strict pattern of expecting parameters in a certain form. If you look back some years you might remember functions like the following:


function doLayerFloat(id,start,end,direction,speed,fade,whatelse,Iforgot){
...
}

This, at least to me is rather annoying as I am terrible at remembering the order the parameters need to be sent in (conditioning in PHP confusion probably). The other issue I kept seeing with this was that if you didn’t want to provide some of the parameters but one of the last ones you had to send empty strings or even null values:


doLayerFloat(‘myDIV’,0,30,null,null,true,null,null){
...
}

// or
doLayerFloat(‘myDIV’,0,30,’‘,’‘,’‘,’‘,’‘){
...
}

This is both confusing and convoluted. Other scripts I have seen work around the issue by using the arguments array, which at least allows a flexible amount of arguments to be sent.


function doLayerFloat(id){
var args = arguments;
for(var i = 1; i < args.length; i++) {
...
}

}

However, my favourite these days is functions that actually take a few defined parameters (or a single one), allow for it to be several things and allow you to send an object as the properties:


function doLayerFloat(id, props){
var elm = typeof id !== ‘string’ ? id : document.getElementById(id);
for (var i in props){
...
}

}

This allows the id to be either an element reference or a string and takes an object as the second parameter in which I can define the order and amount any which way I like (provided the method then tests for each of them and their correct values):


doLayerFloat(‘x’,{start:20,end:30,fade:true});
// or
doLayerFloat(myElm,{fade:true,direction:’right’});

This also allows you to define default values should the properties not be set, something you can do in PHP but not in JavaScript. In PHP, this works:


function foo($bar=2,$baz=’foo’){
}

In JavaScript that can’t be done, but if you use an object you can predefine if the properties are not set:


function doLayerFloat(id, props){
var elm = typeof id !== ‘string’ ? id : document.getElementById(id);
props = props || {};
props.start = props.start || 100;
props.fade = props.fade || false;
}

Do you agree? Or is the object literal syntax still too tricky?