June 2, 2011

JavaScript, and var

Filed under: javascript — Tags: , Himanshu @ 2:16 pm

While working in my current project, I re-learned this hard way.  And I don’t want to make same mistake again, hence noting it here. Many a times you remember something better when noted somewhere.

I had created a javascript that was similar as below:

function Type1(){
    _type = "type1";
    this.show = function() { alert(_type); }
}

function Type2(){
    _type = "type2";
    this.show = function() { alert(_type); }
}

o1 = new Type1();
o2 = new Type2();

o1.show();
o2.show();

And me being ignorant about what I have written, was expecting to see two alerts once with “type1” and another with “type2”.

Case that I had was more complex , hence I took more time to understand the problem, and then note that I haven’t have “var”! The code should be as:

function Type1(){
    var _type = "type1";
    this.show = function() { alert(_type); }
}

function Type2(){
    var _type = "type2";
    this.show = function() { alert(_type); }
}

o1 = new Type1();
o2 = new Type2();

o1.show();
o2.show();

Note and Remember, “var” defines the scope of variable as local!

Powered by WordPress