Referring to Javascript: The Good parts, was trying to build an sort of class prototype object which I could then use to create instances. But using the pattern suggested for creating objects and information hiding via closures, I find I have created a private static member rather than an private instance member.
In this case I am attempting create an "account" object which has a private value (balance) variable which is returned by the balance() method:
<head>
<script>
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {
};
F.prototype = o;
return new F;
};
};
var account = function() {
var value = 0;
return {
"account_name": "",
deposit: function (amount) {
value = value + amount;
},
withdrawal: function (amount) {
value = value - amount;
},
balance: function( ) {
return value;
}
}
}();
</script>
</head>
<body>
<script>
var account1 = Object.create(account);
var account2 = Object.create(account);
account1.account_name = "Mario Incandenza";
account1.deposit(100);
account1.withdrawal(25);
account2.account_name = "Hal Incandenza";
account2.deposit(5100);
account2.withdrawal(2000);
document.writeln("<p>Account name = " + account1.account_name + " Balance: " + account1.balance() + "</p>");
document.writeln("<p>Account name = " + account2.account_name + " Balance: " + account2.balance() + "</p>");
</script>
</body>
Here is the result:
Account name = Mario Incandenza Balance: 3175
Account name = Hal Incandenza Balance: 3175
So seeing the sum of all withdrawals and deposits to both accounts obvious that I've created a static 'class' variable (in javaspeak)
So how to create var value at instance level and keep it hidden/private?