I'm a newbie in JavaScript, and I have two questions.
1) I want to know how to protect variables in JavaScript.
In Java, there are access modifiers(like public, private, default, protected). However, as far as I know JavaScript doesn't have. Following is the JS file(suppose the JS file is associated with HTML file):
var my_purse = 10000; // suppose this value from HTMLElement
var my_bank_account = 10000;
function save_money(money) { // skip exception processing
my_purse = my_purse - money;
my_bank_account = my_bank_account + money;
}
function withdraw_money(money) {
my_bank_account = my_bank_account - money;
my_purse = my_purse + money;
}
I think it is possible to change these variables(my_purse
, my_bank_account
) from outside. So, How can I protect these variables?
Apart from above, is there an (dis)advantage if I declare variables using an object(like below)?
var money = {
my_purse: 10000;
my_bank_account: 10000;
}
2) Dependencies between functions should be avoided?
For example, Suppose the above code adds to the process of opening an account
. Then following is possible.
function save_money(money) { // money == (money1 + money2)
if(first_time) {
open_account(money1);
}
my_purse = my_purse - money2;
my_bank_account = my_bank_account + money2;
}
function open_account(money) { // required money to open an account
my_purse = my_purse - money;
my_bank_account = my_bank_account + money;
}
However, in this case save_money
function is dependent on open_account
function. So I think it looks unstable. Is it right that there is a problem with this kind of code?
Thanks for reading despite of my poor english.