如何将变量 balance 设为私有,同时在文本字段中保留值100.00?
HTML文本字段:
<span type="text" id="txtMyAccountBalance"> </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 ,但是如何?
答案 0 :(得分:4)
在这种情况下,实际上您确实可以使用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控制台并侵入代码中,以将其设置为不同的值。不可能由用户操纵的值是不可能的!
答案 1 :(得分:0)
您可以使用Symbol语法
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