Posted By

Tim_McClure on 04/17/13


Tagged


Versions (?)

Public vs. Private Variables


 / Published in: JavaScript
 

Just as functions can have local variables which can only be accessed from within that function, objects can have private variables. Private variables are pieces of information you do not want to publicly share, and they can only be directly accessed from within the class.

The Person class has been modified to have a private variable called bankBalance. Notice that it looks just like a normal variable, but it is defined inside the constructor for Person without using this, but instead using var. This makes bankBalance a private variable.

  1. function Person(first,last,age) {
  2. this.firstname = first;
  3. this.lastname = last;
  4. this.age = age;
  5. var bankBalance = 7500;
  6. }
  7.  
  8. // create your Person
  9. var Tim = new Person("Tim","McClure",23);
  10.  
  11. // try to print his bankBalance
  12. console.log(Tim.bankBalance);

Report this snippet  

You need to login to post a comment.