Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created January 22, 2013 23:37
Show Gist options
  • Save rwaldron/4599927 to your computer and use it in GitHub Desktop.
Save rwaldron/4599927 to your computer and use it in GitHub Desktop.
class Purse {
private balance;
constructor(balance = 0) {
checkNum(amount); // could also be written private.checkNum(amount)
private.balance = balance;
}
getBalance() { return balance; }
makePurse() { return new Purse; }
deposit(amount, srcPurse) {
checkNum(amount);
private(srcPurse).balance -= amount;
balance += amount;
}
private checkNum(n) {
if (typeof n !== "number")
throw new Error("Number please!");
}
}
// === Expansion ===
let Purse = (function() {
let amp = new WeakMap(); // Perhaps with a GC hint
// Prototype of private object holds private methods
let privateProto = {
checkNum: function(num) {
if (typeof n !== "number")
throw new Error("Number please!");
}
};
function Purse(balance = 0) {
// Initialize the private object
let priv = Object.create(privateProto, {
balance: { writable: true }
});
amp.set(this, Object.seal(priv));
// Constructor body
priv.checkNum.call(this, balance);
priv.balance = balance;
}
Purse.prototype = {
getBalance: function() { return amp.get(this).balance; },
makePurse: function() { return new Purse; },
deposit: function(amount, srcPurse) {
let priv = amp.get(this);
priv.checkNum.call(this, amount);
amp.get(srcPurse).balance -= amount;
priv.balance += amount;
}
}
return Purse;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment