开发者

Possible to scope a javascript variable to a function and that function's recursive calls to itself?

I am in a situation where I have a loop that is calling a function. The function will make recursive calls to itself once called.

Is there a way that I can scope a variable to the function and the chain of recursive calls generated from the first call?

Something like this:

for(var i=0;i<100;i++)
{
  myFunction();
}

function myFunction()
{
   var someNumber = 200;
   someNumber -= 10;
   if( someNumber > 0)
   {
      myFunction();
   }开发者_如何学C
}

where at the second iteration of the first call to someNumber would be 190 and not 200. Is this possible to accomplish?

If there is anything confusing here, please let me know.


Yes, use an inner function to do the recursion:

for (var i = 0; i < 100; i++)
{
    myFunction();
}

function myFunction()
{
    var someNumber = 200;
    (function innerFunction()
    {
        someNumber -= 10;
        if( someNumber > 0)
        {
            innerFunction();
        }
    })();
};

Note, you have a syntax error. Your while needs to be for.

Edit: Perhaps your real code is different and calls for a recursive function, but your example would be much simpler by just using a loop:

function myFunction()
{
    for (var someNumber = 200; someNumber > 0; someNumber -= 10)
    {
    }
};


while(var i=0;i<100;i++)
{
  myFunction(200);
}

function myFunction(someNumber)
{
   someNumber -= 10;
   if( someNumber > 0)
   {
      myFunction(someNumber);
   }
}


Yes and no--you should be able to accomplish the task by passing the value of the variable in as a parameter of myFunction. The first call will need to set the starting value, then pass it along for future invocations to modify.

while(var i=0;i<100;i++)
{
  myFunction();
}


function myFunction(seed) {
    if (seed == undefined)
    {
        seed = 200;
    }

    alert(seed);

    var newSeed = seed - 50;
    if (seed > 0)
    {
        myFunction(newSeed);
    }
};


You want a closure. Well, you might not want it, but it will do what you are asking.

(function() {
    var someNumber=200;
    myFunction=function() {
        someNumber-=10;
        if (someNumber > 0) {
            myFunction();
        }
    }
})();

But properly passing parameters is probably a better idea.


I think using objects would be the way to go if you want to do something where you are actually scoping variables.

function myObject(_someNumber) {
    var someNumber = _someNumber;

    this.myFunction = function() {
        this.someNumber -= 10;
        if(this.someNumber > 0)
        {
           this.myFunction(this.someNumber);
        }
    }
}

for(var i=0;i<100;i++)
{
  new myObject().myFunction(someNumber);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜