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

This is the code I used which worked but I don't understand this part:
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

From my understanding, we store the result of calling askTeller with john as the variable myBalanceMethod. I don't really understand the next part where we again store myBalanceMethod as the variable myBalance. I also don't get why myBalanceMethod has (); at the end of it. I thought it was just a variable and not a function? Could someone please explain this to me. Thanks in advance.


#2

@tyoungg,

What they are trying to make clear,
is that after calling the public-accessable askTeller method

you still don't have the actual value of the property-key -bankBalance

because the askTeller-function returns the name of a function

this function must be executed and then you get the Value of bankBalance.

A two-step approach, as you have to execute-twice.

As the () sign means execute, you could also get the result by using

console.log( john.askTeller()() );