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!

1 Comment »

  1. This is a common mistake which people make when writing closures in JS. As a best practice we should always scope the variables in JS and where required use modules in JS.

    Javascript the good parts by Douglas Crockford is a good book to refer here (in fact its a must read for all JS devs)

    (:

    Comment by Hemanshu Bhojak — January 11, 2012 @ 12:38 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress