Did you know that JavaScript supports "data hiding" inside user defined objects? Consider the differences between how the two properties myVar1 and myVar2 are declared inside the following constructor function:
function MyObject() {
this.myVar1 = "public";
var myVar2 = "private";
this.getMyVar2 = function() {
return myVar2;
}
}
myVar1 can be directly accessed because it was defined using "this", but myVar2 cannot because it was defined using "var"; myVar2 can only be accessed via a "method", e.g. the inner function "getMyVar2", as demonstrated below:
var myObj = new MyObject();
alert(myObj.myVar1); //returns "public"
alert(myObj.myVar2); //returns "undefined"
alert(myObj.getMyVar2()); //returns "private"
Think of "this" as the equivalent of the "public" access modifier in other object oriented languages, and "var" as the equivalent of "private". Read more about this technique at: http://devpapers.com/article/291