[英]How do I make a variable private?
如何将变量余额设为私有,同时在文本字段中保持值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。 如何将可变余额设为私有? 我想,我必须使用无功而不是这个 ,而是如何?
在这种情况下,您实际上可以使用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控制台并侵入代码中,以将其设置为不同的值。 用户无法操纵的值是不可能的!
您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.