views:

38

answers:

1

I have a constructor that has a series of classes and functions within it - in each function I check if the param is set to show the error and output if so. Like so using an inline if. The issue and question is short of keeping two versions is this approach not wise in that each IF has to be evaluated thus adding to the time it takes to perform?

debugSlide =  (bag.debug==1)? console.log("item id =" + bag.itemId) : 0;

How do you do this? Any pointers on where I can find tips on this? Thanks in advance!

A: 

This is exactly the type of problem that polymorphism is good at.

var SomeObject = function( initialDebugger )
{ 
  this.test = function()
  {
    alert( 'Test!' );
    this.debugger.log( 'Executing SomeObject.test()' );
  }

  this.setDebugger = function( newDebugger )
  {
    this.debugger = newDebugger;
  }

  if ( 'undefined' == typeof initialDebugger )
  {
    initialDebugger = new SilentDebugger();
  }
  this.setDebugger( initialDebugger );
}

var SilentDebugger = function()
{
  this.log = function(){}          
}

var FirebugDebugger = function()
{
  this.log = function()
  {
    console.log.apply( window, arguments );
  }
}

var sample = new SomeObject();

sample.test();
sample.setDebugger( new FirebugDebugger() );
sample.test();
Peter Bailey
Awesome. Thanks for this - I will test it out.
uber_n00b