function wallet( initValue ) {
console.log( "init cash: " + initValue )
// "cash" has function scope, it cannot be accessed outside "wallet"
var cash = initValue;
return {
// As we define "spend" and "spendable" inside "wallet",
// both can access "cash".
spend: function( amount ) {
if( amount > cash ){
console.log( "No enough cash to spend: (" + amount + ">" + cash + ")" )
}else{
cash = cash - amount;
console.log( "Spent: " + amount );
}
},
spendable: function() {
console.log( "In wallet: " + cash );
return cash
}
};
}
// We create a wallet for mike
var mike = wallet( 100 );
// With the closure feature, the spendable() and spend() can still
// access "cash" which is:
// (1) defined outside spendable() or spend()
// (2) even after the function which defines "cash" exits.
mike.spendable();
mike.spend( 10 );
mike.spend( 10 );
mike.spendable();
// If we call the wallet() again, we have another closure.
var john = wallet( 100 );
john.spendable();
// The "cash" in wallet is protected. The only way to
// change "cash" is through spend(). This provides a solution for
// data encapsulation as JavaScript object do not protect its member
// at all.
john.cash = 10; // This is not "cash" in wallet().
john.spendable();
// A example of unsafe wallet.
function Unsafewallet( initValue ){
console.log( "init cash: " + initValue )
this.cash = initValue;
this.spend = function( amount){
if( amount > this.cash ){
// Do something
console.log( "Only " + this.cash + " to spend.")
}else{
this.cash = this.cash - amount;
console.log( "Spent: " + amount );
}
}
this.spendable = function(){
console.log( "In wallet " + this.cash );
return this.cash;
}
}
var alice = new Unsafewallet( 100 )
alice.spend( 20 );
alice.spendable();
// cash is not in global space, but it's not protected.
alice.cash = 0;
// alice's wallet is empty, but she hasn't spent that much.
alice.spendable();
"Technology is nothing. What’s important is that you have a faith in people, that they’re basically good and smart, and if you give them tools, they’ll do wonderful things with them.” --- Steve Jobs
JavaScript: Closure
This is a translation from the example of "JavaScript: The good parts", without error checking. All code pieces do not make sense in practical use. They are just for showing language features
Labels:
JavaScript