Why isn't it global?
Javascript has functional scope, so the secret
variable exists only within the scope of the function.
var iAmGlobal = true;
iAmGlobalToo = true; // no var made this an implied global
(function () {
var iExistInThisFunctionsScope = true;
iAmAnImpliedGlobal = true; // omitted var attached this to the global scope
}());
Omitting var
doesn't necessarily make a variable global. What happens is, when a variable isn't found in the current scope, the parent scope is checked. This happens either until the variable is found, or the global
scope is reached. When you accidentally forget var
, you often end up with an implied global.
What are some of the problems of "Implied Global variables"?
Why use getters/setters?
Using closures to create getters/setters allows you to control how the variables are modified. Because in Javascript everything is mutable, anything can be changed by any other thing. This seems cool at first, but you soon realize that you have no control over who or what is changing your variables. Getters and setters allow you to hide the variable in the function's scope, so if something wants to change it, it must go through you.
Here's an example of controlling your variables.
function Foo () {
var privateVar = 1234;
this.get = function () {
return privateVar;
}
this.set = function (x) {
// privateVar doesn't exist in this function's scope,
// but it will be found in the next scope up the chain.
privateVar = x;
}
}
// create an instance
var myFoo = new Foo();
// use the getter/setter
console.log(myFoo.get()); // 1234
myFoo.set(999);
console.log(myFoo.get()); // 999
// try to change privateVar outside
// of the getter/setter
myFoo.privateVar = 'not what you think';
// We didn't actually change the var.
console.log(myFoo.get()); // 999
// We added a new property.
console.log(myFoo.privateVar); // 'not what you think'