24. Accessing Private Variables


#1

Hi I am really stuck with the below code. Can you please help me in fetching the expected results. I suspect the issue with the last piece of the code. Thanks in advance.

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


#2

var myBalance should = to john.getBalance();


#3

The Person object has this

This is a private variable. Private variables are internal to the class(meaning you can only use/see it when you are inside the class).


Thats why you have this function

which will give that variable's value so you should be using that function to get the bankBalance

NB: class properties that start with this. keyword are public attributes


#4

Thanks one and all. I just changed the variable as below and worked fine.

var myBalance = john.getBalance();


#5

The compiled OK version!

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);
john.getBalance();