3

How can I isolate my variable from variable in this function, if his creator forgot for var keyword?

for (var i = 0; i < 4; i++) 
{
    test();
}

function test() 
{
    i = 0;
}
user123444555621
  • 148,182
  • 27
  • 114
  • 126
Matěj Pokorný
  • 16,977
  • 5
  • 39
  • 48

2 Answers2

3

put your for loop in a separated scope:

in a function.

function test(){
  i = 0;
}
function trial(){
  for (var i = 0; i < 4; i++){
    test();
  }
}
trial();

That way only the code and functions inside the trial function can access variables declared at that level.

Sami
  • 648
  • 8
  • 25
3

Same idea than previous answer using scoping but a better way would be to use IIFE:

(function () {
    for (var i = 0; i < 4; i++) {
        test();
    }
})();

http://jsfiddle.net/8vBc5/

A. Wolff
  • 74,033
  • 9
  • 94
  • 155