Németh Péter
Németh Péter

Reputation: 151

Make Javascript local variable to global for recursive loops

I have a recursive function which has a local variable. It calls itself on specific condition. The local variable needs to be updated, but every call it creates a new local variable specific to the current function scope. How can i reach the local variable for access all recursive loop and not to create a new one? Something like __Callee.varname?

The code is:

var addAttribute = function(object,elem)
{
    var attributes = [];

    // only attribute without values
    if ( object instanceof Array )
    {
        for ( var value in object )
        {
            attributes.push(object[value]);
        }
    }
    // attribute with values
    else if ( object instanceof Object )
    {
        for ( var key in object )
        {
            if ( object[key] instanceof Array )
            {
                addAttribute(object[key],elem);
            }
            else
            {
                attributes.push(key+'=\''+object[key]+'\'');
            }
        }
    }
    // Only one attribute
    else if ( typeof object === 'string' )
    {
        attributes.push('\''+object+'\'');
    }
    // Invalid parameter
    else
    {
        console.log('Invalid parameter: '+typeof object);
    }

    console.log('<'+elem+' '+attributes.join(' ').toString()+' />');

}

I do not want to make variable to global because of using this name in other functions and global scope already.

Upvotes: 2

Views: 4249

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074666

The usual thing is to pass it into the function, possibly optionally:

var addAttribute = function(object,elem, attributes) {
    attributes = attributes || [];
    // ....

Then when calling it recursively, pass in the third argument:

addAttribute(object[key], value, attributes);

Here's a much simplified example demonstrating:

function foo(num, array) {
  array = array || [];
  array.push(num);
  console.log("Pushed " + num + ", array = " + JSON.stringify(array));
  if (num < 5) {
    foo(num + 1, array);
  }
}
foo(1);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386650

Use a closure

function fn() {
    function recursiveFunction() {
        // do something with x
        recursiveFunction();
    }
    var x = 0;
    recursiveFunction();
}

Upvotes: 5

Related Questions