Here's an example of the Module Pattern, read the comments to understand how it works:
So, this solves the problem of having a private variable that we don't want to expose. Now lets see an example of a "class" in JavaScript (note: future versions will have class constructs built into the language, I'm just showing how people do it today):
This works, but the property 'firstName', is being used by the getName function, and is public. This means we can just override the property.
How would we create a private property in this case? Well, what if we try the same concept of scoping things to the execution of the constructor function, first attempt:
The function now doesn't have access to the variables, so what if we move this into the scope of the constructor... second attempt:
At first glance, this seems to work, but we actually override the prototype each time the constructor runs... bad! Instead we should rather be defining the function on the actual instance being created:
This then solves the problem of keeping the variables private to each instance. One downside to this then is that each instance is referring to its own function, and not sharing one common function on the prototype, taking up more memory, but giving the advantage of private scope.
For some extra reading on scopes in JavaScript, read this - http://javascript.crockford.com/private.html
Another similar way of doing this is with the Revealing Prototype Pattern, explained in Dan Wahlin's post here - http://weblogs.asp.net/dwahlin/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern