Accessing Private Variables


#1

Hi guys, I'm having trouble writing the code to access the John's account balance, I don't know how to finish it.
The code is supposed to have variable named myBalance (as created at the bottom section) and set its value to John's bank balance. I'm supposed to do this by calling your newly-defined getBalance method for john. Then print myBalance.

Please help me out. Thanks.
Here's the code that i came up with:

function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   this.getBalance = function() {
      // your code should return the bankBalance
      return bankBalance;
   };
}

var john = new Person('John','Smith',30);
console.log(john.bankBalance);

// create a new variable myBalance that calls getBalance()
john.getBalance();
var myBalance = function () {
    console.log(this.bankBalance);
};
myBalance();

#2

i am confused, here you call the method:

john.getBalance();

but then you create another function, i am confused, you don't have to do this, all you have to do, assign the method call to a variable called myBalance:

myBalance = john.getBalance();

that is it, you are over complicating


#3

That works, I thought I was supposed to call john.getBalance first then create a variable that would call myBalance. Thanks :slight_smile:


#4

the instructions:
Then on line 17, create a new variable named myBalance and set its value to John's bank balance. You can do this by calling your newly-defined getBalance method for john. Then print myBalance

it clearly states you need to call the method and store it in myBalance variable. And then print this


#5

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