【问题标题】:How do I make a variable private?如何将变量设为私有?
【发布时间】:2019-06-05 21:23:14
【问题描述】:

如何将变量 balance 设为私有,同时在文本字段中保留值 100.00?

HTML 文本字段:

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

函数如下:

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

var currentAccount = new TAccount ();

currentAccount.balance = 100.0;

这很好用,文本字段显示 100.00 作为余额。如何将变量 balance 设为私有?我想我必须使用 var 而不是 this,但是如何?

【问题讨论】:

标签: javascript dom private


【解决方案1】:

在这种情况下,您确实可以使用var

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;
  }
}

不要将其用于安全性,因为它不安全。人们仍然可以进入 javascript 控制台并侵入代码以将其设置为不同的值。用户无法操作的值是不可能的!

【讨论】:

  • 非常感谢,这几乎是我所希望的。是否可以保留 var balance = 0.0; 并仍然让文本字段 &lt;span type="text" id="txtMyAccountBalance"&gt;&amp;nbsp;&lt;/span&gt; 显示 currentAccount.balance = 100.0;
  • @Senseless 如果你在function TAccount() { ... } 之上定义var txtMyAccountBalance = document.querySelector('#txtMyAccountBalance');,它应该像你以前那样工作! :)
【解决方案2】:

你可以使用符号语法

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

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 2017-04-10
    • 1970-01-01
    • 2012-06-27
    相关资源
    最近更新 更多