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!
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