Link to home
Start Free TrialLog in
Avatar of wallaceni
wallaceni

asked on

javascript puzzle

I have a js like :

/*****/

var a=5;

function test(){
    this.a = 20;
    a=0;
    write(a);
    write(this.a);
    var a;
    write(a);      
}

test();
new test();
Result :  0 20 0 / 0 20 0

but if i change test() to
function test(){
    this.a = 20;
    a=0;
    write(a);
    write(this.a);
    //var a;
    write(a);      
}

result : 0 0 0 / 0 20 0

can someone tell why?
Avatar of JermTheWorm
JermTheWorm
Flag of South Africa image

Apparently curious behaviour.
I'm going to jump to the conclusion that no matter where you put the 'var a;' inside the function it is as if it is at the top, without the 'var a' a refers to 'this.a' because it is the 'closest' a  in scope.
ASKER CERTIFIED SOLUTION
Avatar of Shahzad Fateh Ali
Shahzad Fateh Ali
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@shahzadfatehali Yes I missed that bit, that explains why the 'test()' call vs 'new test()' in the second instance display different results.It doesn't explain why when the test function is changed only by commenting out the 'var a;' line 'this.a' is overwritten by 'a'.
I think if we take a combination of both our answers above we'd be closer to the whole truth ;-)
I already answered that in this case 'a' and 'this.a' refers to the same variable (global scope variable), but if you declare it as 'var a' a new variable will be available in local scope.
@shahzadfatehal: I agree with you, I was just trying to point out there are 4 'calls' to test in wallaceni's example not only 2 he was doing a 'test(); new test();' with the 'var a;' and again with it commented out.