One problem with this scope structure is that it leaves no room for private variables. Consider the following code snippet:
var name = 'Ford Focus'; var year = '2006'; var millage = 123456; function getMillage(){ return millage; } function updateMillage(n) { millage = n; }
These variables and functions are global, which means it would be too easy for code later down the program to accidentally overwrite them. One solution would be to encapsulate them into a function and call that function immediately after defining it.
var car = function(){ var name = 'Ford Focus'; var year = '2006'; var millage = 123456; function getMillage(){ return Millage; } function updateMillage(n) { millage = n; } }();
Nothing is happening outside the function, so we ought to discard the function name by making it anonymous.
(function(){ var name = 'Ford Focus'; var year = '2006'; var millage = 123456; function getMillage(){ return millage; } function updateMillage(n) { millage = n; } })();
To make the functions getValue()
and updateMillage()
available outside the anonymous function, we'll need to return them in an object literal as shown in the following code snippet:
var car = function(){ var name = 'Ford Focus'; var year = '2006'; var millage = 123456; return { getMillage: function(){ return millage; }, updateMillage: function(n) { millage = n; } } }(); console.log( car.getMillage() ); // works console.log( car.updateMillage(n) ); // also works console.log( car.millage ); // undefined
This gives us pseudo-private variables, but the problems don't stop there. The following section explores more issues with variable scope in JavaScript.