This is because of a characteristic of Javascript known as closure. It basically means that if objects are nested, then the inner objects can only access variables from objects outside them. By using the this keyword, your essentially making the variable a property of that object. Variables declared using var will not be accessible to objects that lay outised the method. For an interesting read please check out this link
http://javascript.crockford.com/private.html
Here is an example of an object with a private variable and some public methods and a property. These characteristics are useful as they restrict usage of an object. In this example below we may not want developers tampering with the array so we might just give them a facility to add, facility to remove and they can only see the even indexes : -
function SpecialArray() {
var _array = [];
this.length = _array.length;
this.add = function(stuff) {
// add some stuff to it
}
this.remove = function(stuff) {
// take some stuff out of it
}
this.displayEvenNumbers = function(){
for (var i=0; i< _array.length ; i+=2){
console.log(_array[i]);
}
}
}
johndoesn't have abankBalanceproperty. The variablebankBalancein the constructor functionPersonis not available outside it (because of JavaScript's scoping rules.) Also, JS has no language support for private properties; though, closures can be used to simulate them.var bankBalance, it isn't like Java which it declares a member property, it only defines a local variable. To add a property you have to actually change the instance's property (this.bankBalance), or change it via the prototype (Person.prototype.bankBalance = 7500).