In a chat the concept of private variables in a javascript object came up. I had seen it before but never really had done them before so I thought I would play around with it a bit.
Javascript by default does not have private variables. If you have variables that need to be ‘read-only’ or ‘private’ you can limit it’s visibility with a closure inside your constructor function.
-
-
-
var foo = function(a) {
-
var privateVar = a;
-
this.getPrivate = function() {
-
return a;
-
}
-
this.setPrivate = function(newvar) {
-
a = newvar;
-
}
-
}
-
-
var bar = new foo(1000);
-
alert(bar.getPrivate()); // Alerts 1000
-
bar.setPrivate(‘Hello’); // Sets privateVar to ‘Hello’
-
alert(bar.getPrivate()); // Alerts ‘Hello’
-
alert(bar.privateVar); // Alerts ‘undefined’
-
-
