Created
October 4, 2015 22:46
-
-
Save baileyparker/bf670444b4f144a3c1cd to your computer and use it in GitHub Desktop.
OO Javascript Example
This file contains hidden or 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
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; |
This file contains hidden or 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
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