var boxDefaults:Object = {x:10, y:10, width:100, height:100, lineThickness:0, lineColor:0x000000, lineAlpha:1, fillColor:0xCCCCCC, fillAlpha:1}
function drawBox(params:Object=null):void {
var p:Object=setDefaults(boxDefaults, params);
graphics.lineStyle(p.lineThickness, p.lineColor, p.lineAlpha);
graphics.beginFill(p.fillColor, p.fillAlpha);
graphics.drawRect(p.x, p.y, p.width, p.height);
}
function setDefaults(defaults:Object, params:Object=null):Object {
if (params==null) {
params = new Object();
}
for (var key:String in defaults) {
if (params[key]==null) {
params[key]=defaults[key];
}
}
return params;
}
// test it out... notice that all object properties are optional and have default values
drawBox();
drawBox({x:200, y:200, lineColor:0xFF0000, lineThickness:2, fillColor:0xCCCC00});
drawBox({x:200, y:320, width:50, height:150, lineAlpha:0, fillColor:0x416CCF});
This is a technique I’ve been using recently… inspired by tweening engines. I find this to be suitable when a function or object constructor has lots and lots of arguments (80% of the time if I have a function or object constructor with too many arguments I re-think my design, but every now and then I use this technique).
Basically, the function or object constructor takes one argument of type Object – once passed into the function this Object argument is passed to the setDefault() function which populates it with any properties that it’s missing – each property has a default value. As a result you end up with an easy to read function call with a variable number of arguments and well thought out default values.
This snippet just draws a box (not very interesting or usefull) – I wanted to showcase the technique using a simple function. As a real world example… I recently used this technique in a mini-library I created for use with Box2D… will be posting the library in the next few days…. it’s a library for fast prototyping and custom rendering.
very useful trick. Thank you , Zevan.
you’re welcome – the idea came from tweening engines like Tweenlite, Tweener etc…