example:
function Foo() {
this.bla = 1;
var blabla = 10;
blablabla = 100;
this.getBlabla = function () {
return blabla; // exposes b
Variables declared with var
inside a function used as a constructor will, like all other variables declared with var
inside any function, be visible only during the execution of that function (unless the value is closed over using closures).
In other words, blabla
is effectively invisible outside the function:
var foo = new Foo();
console.log(foo.bla); // 1
console.log(foo.blabla); // throws NameError
By defining functions which close over these variables, they become the closest thing JavaScript has to "private" variables:
function Foo() {
this.bla = 1;
var private = 1;
this.increment = function() {
++private;
}
this.getPrivateValue = function() {
return private;
}
}
foo = new Foo();
console.log(foo.bla); // 1
foo.bla = 6; // legal
console.log(foo.bla); // 6
console.log(foo.getPrivateValue()); // 1
// console.log(foo.private); // would throw an error
foo.increment(); // legal
console.log(foo.getPrivateValue()); // 2
// foo.getPrivateValue() = 5; // syntax error. Still can't reassign to private no matter what you try!