0

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.

hje
  • 25
  • 5
  • You can't declare variables directly within an object literal. Use `const` to declare constants, and `let` to declare variable variables. See https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – Teemu May 12 '20 at 18:10
  • `var money = { my_purse = 10000; my_bank_account = 10000; }` is wrong, use `var money = { my_purse: 10000, my_bank_account: 10000 }` – StudioTime May 12 '20 at 18:32
  • oh, I was mistaken. thanks. – hje May 12 '20 at 18:34
  • thanks for reference. I'll read it. – hje May 12 '20 at 18:36

1 Answers1

0

The shortest answer I can give is that those variables won’t be accessible if you wrap everything in an “instantly invoked functional expression” or just a function in general; function scopes protect variables.

(function () {
  // your inaccessible code here
})()

Another good rule to guide is to always use const rather than var if possible, some rare times you may use let

neaumusic
  • 10,027
  • 9
  • 55
  • 83