Skip to content

Instantly share code, notes, and snippets.

@frio80
Created October 20, 2011 03:15
Show Gist options
  • Save frio80/1300333 to your computer and use it in GitHub Desktop.
Save frio80/1300333 to your computer and use it in GitHub Desktop.
Accessing privates variables in shared methods on the prototype
// Was always interested if you can share private variables in prototyped methods. And it looks like you can!
function Bank(name) {
this.name = name;
this.messages = [];
}
Bank.prototype = (function() {
var money_total = 500000;
return {
withdraw : function(amt) {
if (amt > money_total) {
this.messages.push("The bank does not have enough money!");
return false
}
money_total -= amt;
this.messages.push(amt + " withdrawn from total leaving " + money_total);
return true;
},
getTotal : function() {
return money_total;
}
}
}());
var branch1 = new Bank("NY")
var branch2 = new Bank("CT")
branch1.withdraw(400000); // true
branch1.messages; // ["400000 withdrawn from total leaving 100000"]
branch2.withdraw(400000); // false
branch2.messages; // ["The bank does not have enough money!"]
// Version 2
// Heck, you could even do:
function Bank(name) {
// private
var money_total = 500000;
// public
this.name = name;
this.messages = [];
// Define prototype methods
Bank.prototype.withdraw = function(amt) {
if (amt > money_total) {
this.messages.push("You don't have enough money!");
return false
}
money_total -= amt;
this.messages.push(amt + " withdrawn from total leaving " + money_total);
return true;
};
Bank.prototype.getTotal = function() {
return money_total;
};
}
var branch1 = new Bank("NY")
var branch2 = new Bank("CT")
branch1.withdraw(400000); // true
branch1.messages; // ["400000 withdrawn from total leaving 100000"]
branch2.withdraw(400000); // false
branch2.messages; // ["The bank does not have enough money!"]
@mathiasbynens
Copy link

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