25. Private Methods


#1


https://www.codecademy.com/courses/objects-ii/4/4?curriculum_id=506324b3a7dffd00020bf661#


I am confused as to why this code works. Can someone explain it in more detail than what was provided by the lesson?


function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   var returnBalance = function() {
      return bankBalance;
   };
       
   // create the new function here
   this.askTeller = function() {
       return returnBalance;
   }
}

var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);


#2

bankBalance is now private, it can't be accessed directly:

var john = new Person('John','Smith',30);
console.log(john.bankBalance) # will give undefined

#4

Thanks. I do see that it is private, but the following code:

var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

doesn't make sense to me. Why could I not just do john.returnBalance from the beginning? I see it returns undefined, but why does this happen? And why do we do the following two lines after:

var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();

I don't understand what the purpose of this is. It seems to me we are turning a private method(returnBalance) into a public function(askTeller) and then defining that as a variable myBalanceMethod, which we then turn into another variable? Where am I going wrong here, and why do we do this?


#5

var john = new Person('John','Smith',30);
console.log(john.returnBalance);

This code, because bankBalance is now private, we can't access it.

in order to access the private variable, we need to make a public method:

this.askTeller = function(){
       return returnBalance;
   };

which returns the private method. Now we can use this public method to access the private variable:

var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

#6

To add an additional take here as I had the same question!

For the this bit of the code:
console.log(john.returnBalance); // If you run this code it logs as undefined. If you delete this bit of code, what remains is the bank balance because,

This second portion here:
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

// gives us the correct bank balance because it first creates a variable that creates the ask teller function and then logs that answer to the screen.

Hope this helps. :slight_smile:


#7

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