Last active
February 7, 2017 17:12
-
-
Save SK-CSE/be3c1ae256791b05793f2f11a16fe57d to your computer and use it in GitHub Desktop.
OOPS in JavaScript
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
// with prototype | |
function BankAccount(amount) { | |
this.balance = amount; | |
} | |
BankAccount.prototype.deposit = function(amount) { | |
this.balance += amount; | |
} | |
BankAccount.prototype.withdraw = function(amount) { | |
if (amount <= this.balance) { | |
this.balance -= amount; | |
} | |
if (amount > this.balance) { | |
console.log("Insufficient funds"); | |
} | |
} | |
BankAccount.prototype.toString = function() { | |
return "Balance: " + this.balance; | |
} | |
var account = new BankAccount(500); | |
account.deposit(1000); | |
console.log(account.toString()); // Balance: 1500 | |
account.withdraw(750); | |
console.log(account.toString()); // Balance: 750 | |
account.withdraw(800); // displays "Insufficient funds" | |
console.log(account.toString()); // Balance: 750 | |
// without prototype | |
function BankAccount(amount) { | |
this.balance = amount; | |
this.deposit = deposit; | |
this.withdraw = withdraw; | |
this.toString = toString; | |
} | |
function deposit(amount) { | |
this.balance += amount; | |
} | |
function withdraw(amount) { | |
if (amount <= this.balance) { | |
this.balance -= amount; | |
} | |
if (amount > this.balance) { | |
console.log("Insufficient funds"); | |
} | |
} | |
function toString() { | |
return "Balance: " + this.balance; | |
} | |
var account = new BankAccount(500); | |
account.deposit(1000); | |
console.log(account.toString()); // Balance: 1500 | |
account.withdraw(750); | |
console.log(account.toString()); // Balance: 750 | |
account.withdraw(800); // displays "Insufficient funds" | |
console.log(account.toString()); // Balance: 750 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment