Created
October 20, 2011 03:15
-
-
Save frio80/1300333 to your computer and use it in GitHub Desktop.
Accessing privates variables in shared methods on the prototype
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
// 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!"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Performance tests: http://jsperf.com/function-prototype-with-private-variables