Skip to content

Instantly share code, notes, and snippets.

@SK-CSE
Last active February 7, 2017 17:12
Show Gist options
  • Save SK-CSE/be3c1ae256791b05793f2f11a16fe57d to your computer and use it in GitHub Desktop.
Save SK-CSE/be3c1ae256791b05793f2f11a16fe57d to your computer and use it in GitHub Desktop.
OOPS in JavaScript
// 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