Skip to content

Instantly share code, notes, and snippets.

@knd
Last active December 10, 2015 18:08
Show Gist options
  • Save knd/4472786 to your computer and use it in GitHub Desktop.
Save knd/4472786 to your computer and use it in GitHub Desktop.
Some code to demonstrate closured variable in JavaScript.
function hellKitchen() {
var knd = "chef";
function hellKitchen101() {
console.log(knd);
knd = "assistant";
}
hellKitchen101();
console.log(knd); // I'm now an 'assistant'
}
hellKitchen();
// another example
var bankAccount = (function() {
var transaction;
var balance = 0;
function init() {
transaction = {
accountHolder: "knd",
deposit: function(amount) {
if (amount > 0) {
balance += amount;
return balance;
}
return balance;
},
withdraw: function(amount) {
if (balance - amount >= 0) {
balance -= amount;
return balance;
}
return balance;
},
currentBalance: function() {
return balance;
}
};
}
init();
return transaction;
})();
console.log(bankAccount.accountHolder); // 'knd'
console.log(bankAccount.currentBalance()); // 0
console.log(bankAccount.deposit(100)); // 100
console.log(bankAccount.deposit(300)); // 400
console.log(bankAccount.withdraw(500)); // 400. Transaction couldn't proceed.
console.log(bankAccount.withdraw(400)); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment