I didn’t take any official course of Javascript.
I often read this in tutorials:
function Bank(name) {
this.name = name;
var balance = 100;
// *my question here* method to access balance
this.getBalance = function() {
return balance * 0.9 ;
};
}
var myBank = new Bank("My Bank");
console.log( myBank.getBalance() );
Why do developers use getBalance() instead of getBalance?
I think “getBalance” is easier to read, but no tutorial use this:
// *my question here* method to access balance
this.getBalance = balance * 0.9 ;
then
console.log( myBank.getBalance );
I didn’t see any tutorial to write using above style, even it is simpler. So:
Is there any different between 2 style of codes? Is there any concern to avoid .getBalance to operate the private variable?
Thanks in advance to explain.
You must understand the different between variable, function and function call. This is variable:
The value of
getBalancevariable is computed once when the code is executed. Every time you accessgetBalance(without parentheses), previously computed value is returned.There is an important implication of using
getBalancevariable. If you modify underlyingbalancevariable in the future,getBalancewon’t reflect that change because it was computed using oldbalancevalue.In the case below:
getBalanceis also variable but it points to a function, not to a simple value. If you access it like variable, you will get a function reference:You can now call that function using
fun(), butfunreference itself (same asthis.getBalance) isn’t very useful in your case.And of course you can call the function by using
this.getBalance(). The semantic difference is as follows: every time you callgetBalance(), the body of the function is executed. This means the value ofbalanceis read again andgetBalance()return value is always up to date.As you can see there is a huge difference between assigning a function and assigning a simple value (like number) to a variable. Depending on which approach you choose, it will have different implications. You must learn about functional side of JavaScript in order to fully utilize its power.