24.Accessing Private Var


#1



I pass the question. In my console.log it prints out undefiend and ReferenceError: getBalance is not defined.
What am I doing wrong?


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 getBalance;
   };
}

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

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


#2

@leftthumb,
You will have to change your return in the getBalance() Method
using

return bankBalance;

The error you get using

console.log(john.bankBalance);

is the proof, that you cannot access a so-called private Property directly.

To get access to the private Property you will have to use a so-called getter Method
After you made the change to the return statement as stated above
in your
console.log(john.getBalance());

================================================

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);  //<== gives an error
console.log(john.getBalance());

#3

Hi,
I am not sure what you mean by

console.log(john.bankBalance); //<== gives an error

As I understand it that is the undefined.

I rewrote the code...
i get the right console log output but i dont pass the section...Oops, try again. The variable myBalance should be set to the result of john.getBalance()

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


#4

@leftthumb,
In your code you are using the new keyword........

Remove this new keyword
like

var myBalance= john.getBalance();

http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript


#5

ohhh.
thank you very much.