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?
wallaceniAsked:
Who is Participating?
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
Actually this behavior is related to the scope and caller of the function. if you see the calls you have made
are
test();
new test();

Open in new window


In first call of the function the default scope of 'this' i.e, window will be used to 'a' or 'this.a' will refer to same variable,

whereas in second call you have used 'new' keyword which will call the function as , constructor of the object and 'this' will refer to the reference of the object return, here 'a' and 'this.a' are different.
0
 
JermTheWormCommented:
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.
0
 
JermTheWormCommented:
@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 ;-)
0
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
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.
0
 
JermTheWormCommented:
@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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.