Private Methods: why is it necessary to declare so many variables?


#1


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


In this exercise, I had to create a public function to call a private function. In the second part where I'm calling all the functions, why is it necessary to loop through so many declared variables to call the function? Why do I have to input:

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

How come putting something like this won't work?

console.log(john.askTeller());



Here's the full code:

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

Because you skipped a step, what does john.askTeller return? What do you need to do with that value to get the balance? What did you do in the other version? Just add that, nothing to do with whether you store the intermediary results or not, you simply have to do the same actions.

Sometimes it's useful to break up expressions into smaller parts and name them so that each expression is readable. These function names should do that on their own though, perhaps their names aren't the greatest. It could instead be:

console.log(new Account('John', 'Smith', 30).getBalanceMethod()());

#3

Ah I see! Thanks for the explanation.


#4

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