Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active December 11, 2015 06:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domenic/4562796 to your computer and use it in GitHub Desktop.
Save domenic/4562796 to your computer and use it in GitHub Desktop.
class Purse {
private balance;
constructor(balance = 0) {
this.@checkNum(amount);
this.@balance = balance;
}
getBalance() { return this.@balance; }
makePurse() { return new Purse; }
deposit(amount, srcPurse) {
this.@checkNum(amount);
srcPurse.@balance -= amount;
this.@balance += amount;
}
private checkNum(n) {
if (typeof n !== "number")
throw new Error("Number please!");
}
}
// === Expansion ===
let Purse = (function() {
let amp = WeakMap(true);
// 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;
})();
@Nathan-Wall
Copy link

How about also changing the declaration private checkNum(n) also to just @checkNum(n)?

@domenic
Copy link
Author

domenic commented Jan 18, 2013

@Nathan-Wall hmm, not sure. I think private checkNum(n) makes sense given that it's a peer of private balance? I.e. use private for declarations, @ for access.

@claudepache
Copy link

Nice proposal. I suggest the following amendments:

  • possibly dropping the private balance declaration, for the statement this.@balance = balance is sufficient. So, it would work the same way as public properties, which are not declared. OTOH, forcing them to be declared is better for debugging;
  • like Nathan, changing private checkNum(n) { ... } into @checkNum(n) { ... }. Indeed, it would be more consistent with the use of getBalance() { ... } instead of function getBalance() { ... }, where the context only tells the difference between declaration and access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment