简体   繁体   中英

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

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);                    
   }
}

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);                    
   }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM