25. Private Methods


#1

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
    var myBalance = myBalanceMethod();
    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);

That was the code.

This is the code that I am having trouble with:

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

I don't know what I am doing wrong ? !!!


#2

That line should not be there.

Also, if you look closely, you'll see that your class is not terminated (closed) with an end brace }. This should be throwing an error in the console.

Once the repairs are done, this line should give an expected error (the instructor wants us to see this).

console.log(john.returnBalance);

The reference error is thrown because the john instance does not have a 'returnBalance' property. It is a class variable that can only be accessed by a method in the class, hence the term, private.

var myBalanceMethod = john.askTeller();

The return value from john.askTeller() is a function reference in the form of a string. Notice that only the reference is returned, not an invocation of the function. This is what the string looks like:

"function() {
      return bankBalance;
   }"

and it is now cached in myBalanceMethod. To read the balance, we invoke this function.

var myBalance = myBalanceMethod();

#3

var myBalanceMethod = john.askTeller();
console.log(john.returnBalance);
this.askTeller = function() {
return bankBalance;
}
I'm sorry I am not really good at this. This is what I fixed and its till giving me a syntax error?


#4

The above belongs where you had it, inside the class definition. You are so close but somehow confusing things. Would it help if we repost your entire code?


#5

That would help a lot Thank you


#6

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);

#7

Thank you sooooo much !!! It worked :slight_smile: