Private variables in javascript

09.04.2009

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.

  1.  
  2.  
  3. var foo = function(a) {
  4.         var privateVar = a;
  5.         this.getPrivate = function() {
  6.                 return a;
  7.         }
  8.         this.setPrivate = function(newvar) {
  9.                 a = newvar;
  10.         }
  11. }
  12.  
  13. var bar = new foo(1000);
  14. alert(bar.getPrivate()); // Alerts 1000
  15. bar.setPrivate(‘Hello’); // Sets privateVar to ‘Hello’
  16. alert(bar.getPrivate()); // Alerts ‘Hello’
  17. alert(bar.privateVar);   // Alerts ‘undefined’
  18.  
  19.  

Leave a Reply

© Copyright 2009, JoshMattVander. Powered by Wordpress
Valid XHTML 1.0 Strict : Valid CSS 2