Archive for the ‘OOP’ Category

Oh what tangled webs we weave…

Wednesday, March 15th, 2006

Because I didn’t want to foul up the namespace in my JavaScript tabber, I attached the tabber object directly to the DOM element it was controlling, then I had to add several “pointers” back and forth between the object and various DOM elements so they could get to each other without relying on any variables. When you look at it like this, it seems rather complicated:

Tabber diagram

I wonder if there are any issues with “memory leaks” due to IE’s faulty garbage collection… let me know if you notice anything.

Update: Hold the presses, I found a few more links. Some of these pointers are not used except when creating new elements to add into the DOM, so I can probably just switch those to use local variables. It shouldn’t matter, but with IE’s faulty garbage collection, who knows if it might cause problems.

Tabber diagram 2

Update :o h good god, the squiggly lines have taken over!


Easier JavaScript object constructor arguments

Tuesday, March 7th, 2006

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.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