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:

 1: function Type1(){
 2:     _type = "type1";
 3:     this.show = function() { alert(_type); }
 4: }
 5: function Type2(){
 6:     _type = "type2";
 7:     this.show = function() { alert(_type); }
 8: }
 9: o1 = new Type1();
 10: o2 = new Type2();
 11: o1.show();
 12: 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:

 1: function Type1(){
 2:     var _type = "type1";
 3:     this.show = function() { alert(_type); }
 4: }
 5: function Type2(){
 6:     var _type = "type2";
 7:     this.show = function() { alert(_type); }
 8: }
 9: o1 = new Type1();
 10: o2 = new Type2();
 11: o1.show();
 12: o2.show();

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

Powered by WordPress