Last active
December 11, 2015 06:58
-
-
Save domenic/4562796 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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.
Nice proposal. I suggest the following amendments:
- possibly dropping the
private balance
declaration, for the statementthis.@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 ofgetBalance() { ... }
instead offunction 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
How about also changing the declaration
private checkNum(n)
also to just@checkNum(n)
?