25. Private Methods (JavaScript)


#1

Hey Team, why isn't this code working?

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

First thing to notice would be that the closing } for the object is missing.


#3

why must have 'var myBalance = myBalanceMethod();'
any idea??


#4

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


#5

Why does this code work. What makes your code work in comparison to his? It would be nice to provide that explanation for others who will come across this post with the same issue


#6

I'm asking why must have 'var myBalance = myBalanceMethod();' , not about the working code.
But still Thank you for ur working code that maybe will help others


#7

the same thing happened to me, for some reason the last } on this part disappeared :

// create the new function here
this.askTeller = function() {
return returnBalance;
};
}

^ this one here ends the Person object and some how mine ended up looking like this:

// create the new function here
this.askTeller = function() {
return returnBalance;
};

notice ^ that last '}' was missing. don't know what happened just make sure everything is closed properly.


#8

I have the same question. Why can't we just say -->
var myBalanceMethod = john.askTeller();
console.log(myBalanceMethod);

would that be enough? I tried it and it gave me an error not sure why!