-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathoop-ex.js
79 lines (57 loc) · 1.5 KB
/
oop-ex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//object literal
let houses = {
Nairobi: "Harambee House",
Nakuru: "Times Tower",
Juja: "Hall 6"
}
//object constructor
let house = new Object();
// map constructor
const cars = new Map();
// constructor function
function Car(make, model, year){
this.make = make;
this.model = model;
this.year = year;
}
let myCar = new Car("Tesla", "Model S", 2020)
console.log(myCar)
//prototype
Car.prototype.horse_power = 1000;
Car.prototype.drive = function(){
console.log("Vroom vroom")
};
console.log(myCar.horse_power)
console.log(myCar.drive())
//inheritance
function ElectricCar(make, model, year){
Car.call(this, make, model, year);
}
ElectricCar.prototype = Object.create(Car.prototype);
ElectricCar.prototype.constructor = ElectricCar;
let myElectricCar = new ElectricCar("Tesla", "Model S", 2020)
console.log(myElectricCar.horse_power)
//encapsulation
function BankAccount(balance){
let _balance = balance;
this.getBalance = function(){
return _balance;
}
this.deposit = function(amount){
_balance += amount;
}
this.withdraw = function(amount){
if(_balance >=amount){
_balance -= amount;
console.log("Withdrawal successful")
} else {
console.log("Insufficient funds")
}
}
}
let myAccount = new BankAccount(25000);
console.log(myAccount.getBalance());
myAccount.deposit(35000);
console.log(myAccount.getBalance());
myAccount.withdraw(65000);
console.log(myAccount.getBalance());