24. Accessing private variables


#1

Hi,

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

When I run this code, I get the error message: "Oops, try again. Remember to still print john.bankBalance!" I wonder what is wrong with it.

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


// create a new variable myBalance that calls getBalance()
var myBalance = john.getBalance();
console.log(myBalance);

#2

HI you just need to add this line

console.log(john.balance)

just after john object.... just like the error says
Oops, try again. Remember to still print john.bankBalance!


#3

The result seems to be right. There reads undefined 7500.

Does there read first undefined, because there is no way to print John'n bankBalance without using getBalance method? I mean it is not possible to print it by just running

console.log(john.bankBalance);


#4

Does there read first undefined, because there is no way to print John'n bankBalance without using getBalance method?

Yes, you right


#5

You can refer to this code if you are having trouble

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()
var myBalance = john.getBalance();
console.log(myBalance);

#6

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