25. Private Methods - Question


#1


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


Got through the exercise but I don't really understand what's happening at the bottom with the pre-filled variables from codecademy. Specifically, this part:

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

Why do we have to create the myBalanceMethod variable and then the myBalance variable? Additionally, how would you know to put parentheses after the myBalanceMethod Variable?


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

Very good question.
I do not understand why we need this part either:

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

It would be ver great if somebody could answer this question!


#3

I was just about to post something about this exact portion of the code. Excellent question. Hopefully we can get an answer soon about this.


#4

The example is a bit short. As I understand it it is that you would only know the (private) method which would call returnBalance in which more could happen than just returning the bankBalance directly.

This would be to ensure the safety of the variables and work with them just via functions.

Imagine the real world (of the 1960's :wink: ) when you would enter the bank and ask the cashier to tell you your balance. The bank would not neccesseraly want you to look at it directly yourself, because you might see something what you're not supposed to or just change your balance in your favour.

I am sure someone can (and will) elaborate more.


#5

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