Easier JavaScript object constructor arguments

I stumbled across a nice technique when making my JavaScript tabifier.

Say you have a JavaScript object constructor:

function myObject() {
this.firstName = 'Patrick';
this.lastName = 'Fitzgerald';
var o = new myObject();
o.firstName = 'Lauren';
o.lastName = 'Fitzgerald';

But you want to make it easy to override the properties, so you pass them in as arguments to the constructor:

function myObject(firstName,lastName) {
if (firstName) { this.firstName = firstName; }
else { this.firstName = 'Patrick'; }
if (lastName) { this.lastName = lastName }
else { this.lastName = 'Fitzgerald'; }
var o = new myObject('Lauren','Fitzgerald');

Fine and dandy, but what if you start adding more properties? Suddenly your object constructor is getting complicated, ugly, and confusing:


Instead set up all the default values for your object properties, and use a single argument to override the values:

function myObject() {
this.firstName = 'Patrick';
this.lastName = 'Fitzgerald';
this.phone = '';
this.ssn = '';
for (var n in arguments[0]) { this[n] = arguments[0][n]; }

By adding one line to your object constructor, you have given the user the flexibility to change any of the default parameters. Furthermore, they can specify the parameters in any order, and leave out the ones they don’t want to change.

Compare the two:

var o = new myObject('Lauren','','','','brown'});
var o = new myObject({firstName:'Lauren',hairColor:'brown'});

This also gives the user the ability to add custom parameters or even methods to the object, all with a single call to the object constructor.

See also: Using JavaScript objects for function arguments with default values

Leave a Reply