Scott
Scott

Reputation: 3019

Is there a better way to write these functions?

I'm not a javascript programmer by any means, but this has been annoying me for the longest while,

is there a better way to write these two seperate functions. As in a single function?

function showAll()
{
   var collection = getElementsByClassName("dealHolder");
   for (var x = 0; x < collection.length; x++) 
   {
      setParentTrue(collection[x].parentNode);                    
   }
}

function setParentTrue(obj) {
     if (obj.id != "deal") 
     {
          obj.id = "true";
          setParentTrue(obj.parentNode);
     }
     else
     {
        obj.style.display = 'block';
     }
}

Can I declare a function within another and recursively call it? any time I need to recurse I always seem to be creating a separate function specifically for it

Cheers for the advice

Upvotes: 0

Views: 105

Answers (3)

BonyT
BonyT

Reputation: 10940

Actually - writing a separate function to hold what occurs within a loop is good practise so I would not change what you have above.

Actually - no I take that back - in this case the function within the loop is unlikely to be usable to anyone else, so I'd go for one of the examples below. Nested within the same object, but still separate function.

Upvotes: 1

Niklas Wulff
Niklas Wulff

Reputation: 3524

Yes, you can declare a function within a function, as functions are objects.

function showAll()
{

    var setParentTrue = function (obj) {
         if (obj.id != "deal") 
         {
              obj.id = "true";
              setParentTrue(obj.parentNode);
         }
         else
         {
            obj.style.display = 'block';
         }
    }

   var collection = getElementsByClassName("dealHolder");
   for (var x = 0; x < collection.length; x++) 
   {
      setParentTrue(collection[x].parentNode);                    
   }
}

Upvotes: 1

Jason Miesionczek
Jason Miesionczek

Reputation: 14448

function showAll()
{
   var collection = getElementsByClassName("dealHolder"),
       x = 0,
       setParentTrue = function(obj) {
        if (obj.id != "deal") 
        {
            obj.id = "true";
            setParentTrue(obj.parentNode);
        }
        else
        {
            obj.style.display = 'block';
        }
   };
   for (x = 0; x < collection.length; x++) 
   {
      setParentTrue(collection[x].parentNode);                    
   }
}

Upvotes: 1

Related Questions