0

How do I make the variable balance private, and at the same time keep the value 100.00 in the textfield?

HTML-textfield:

<span type="text" id="txtMyAccountBalance">&nbsp;</span>

Here is the function:

function TAccount()
  {
      this.balance = 0.0;
      this.printOut = function () {
          txtMyAccountBalance.innerText = this.balance.toFixed(2);
      }
  }

var currentAccount = new TAccount ();

currentAccount.balance = 100.0;

This works quite good, and the textfield shows 100.00 as the balance. How do I make the variable balance private? I think I have to use var instead of this, but how?

Senseless
  • 99
  • 1
  • 8
  • Possible duplicate of [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes) – John Montgomery Jan 10 '19 at 23:21
  • Possible duplicate of [JavaScript private methods](https://stackoverflow.com/questions/55611/javascript-private-methods) – Matthew Herbst Jan 10 '19 at 23:24

2 Answers2

4

In this case you can actually use var indeed!

function TAccount() {
  var balance = 0.0; // This is not accessible outside of this function, making it practically "private"

  this.printOut = function () {
    // It feels a bit weird, but here we "just" use the balance variable that is defined outside this function
    txtMyAccountBalance.innerText = balance.toFixed(2);
  }

  this.doubleBalance = function() {
    // Same way we can change it by re-assigning
    balance = balance * 2;
  }
}

Do not use this for security though, as it is not secure. People can still go in the javascript console and hack their way into the code to set it to different values. A value that is impossible to be manipulated by a user is not possible!

Michiel Dral
  • 3,932
  • 1
  • 19
  • 21
  • Thanks alot, this is almost what I was hoping for. Is it possible to keep the `var balance = 0.0;` and still get the textfield ` ` to show the `currentAccount.balance = 100.0;` ? – Senseless Jan 10 '19 at 23:58
  • @Senseless if you define `var txtMyAccountBalance = document.querySelector('#txtMyAccountBalance');` above `function TAccount() { ... }`, it should work just like how you did it before! :) – Michiel Dral Jan 11 '19 at 00:07
0

You can use the Symbol syntax

var TAccount = (function() {

    var balanceSymbol = Symbol('balance');

    TAccount.prototype.setBalance = function(BAL) {
        this[balanceSymbol] = BAL;
    }

    TAccount.prototype.getBalance = function() {
        return this[balanceSymbol];
    }

    TAccount.prototype.printOut = function () {
        txtMyAccountBalance.innerText = this.balance.toFixed(2);
    }


});

var currentAccount = new TAccount();

currentAccount.setBalance(100.0);
console.log(currentAccount.balance); // undefined
console.log(currentAccount.getBlance()); // 100
stillatmylinux
  • 1,399
  • 13
  • 25