Skip to content

Instantly share code, notes, and snippets.

@baileyparker
Created October 4, 2015 22:46
Show Gist options
  • Save baileyparker/bf670444b4f144a3c1cd to your computer and use it in GitHub Desktop.
Save baileyparker/bf670444b4f144a3c1cd to your computer and use it in GitHub Desktop.
OO Javascript Example
var BankAcct = (function() {
// The BankAcct function will execute when it is new'ed,
// so this.name and this.balance will be set
function BankAcct(name) {
this.name = name;
this.balance = 100; // starting money
}
// These functions will be available on any new BankAcct() objects
BankAcct.prototype.changeName = function(newName) {
this.name = newName;
};
BankAcct.prototype.spend = function(amount) {
if((this.balance - amount) <= 0) {
console.log('You are out of money :(');
} else {
this.balance -= amount;
console.log('You have $' + this.balance.toFixed(2) + ' in your bank account');
}
};
return BankAcct;
})();
module.exports = BankAcct;
var BankAcct = require('./BankAcct');
var accountOne = new BankAccount("Test Account"),
accountTwo = new BankAccount("Vacation Fund");
console.log(accountOne.balance); // $100
console.log(accountTwo.balance); // $100
accountOne.changeName("Retirement");
console.log(accountOne.name); // "Retirement"
accountOne.spend(99);
console.log(accountOne.balance); // $1
accountTwo.spend(50);
console.log(accountTwo.balance); // $50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment