Why would you do this - private variables with public access


#1

Lesson 25 - Private Methods

My code works, but I wonder why you would create a private variable and then include a public method to access that data. Wouldn't you just leave it public if you were going to add that public method?

I'm interested, what is an application for this?
Thanks

function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   this.getBalance = function() {
      return(bankBalance);
   };
}

#2

Allowing the object to be in control of its integrity, outside code should not be changing any of its internals.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.