-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject-oriented programming.js
More file actions
309 lines (281 loc) · 8.75 KB
/
object-oriented programming.js
File metadata and controls
309 lines (281 loc) · 8.75 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//difference between FP and OOP for the same task
// functional
var shoes = 100;
var stateTax = 1.2;
function totalPrice (shoes, tax) {
return shoes * tax;
}
var toPay = totalPrice (shoes, stateTax);
console.log (toPay);
// object-oriented
var purchase1 = {
shoes: 100,
stateTax: 1.2,
totalPrice: function () {
var price = this.shoes * this.stateTax; // 'this' approach allows for the reuse of existing code
//'this' keyword essentially means this object
console.log('Total price is ', price);
}
}
purchase1.totalPrice ();
// polymorphism
class Plant { // this is a super-class
needWater () {
console.log('Flowers need water');
}
}
class Orchid extends Plant { // this sub-class inherits needWater() method from the super-class
needWater () {
super.needWater ();
console.log ('I need water regularly'); // and extends with an additional console log
}
}
class Cactus extends Plant {
needWater () { // this doesn't inherit the needWater() class; it has its own implementation, although the class itself extends the super-class
console.log ('Little water');
}
}
var pinkOrchid = new Orchid ();
var smallCactus = new Cactus ();
pinkOrchid.needWater (); // I need water regularly
smallCactus.needWater (); // Little water
// creating classes - example
class Bird {
useWings() {
console.log("Flying!")
}
}
class Eagle extends Bird {
useWings() {
super.useWings()
console.log("Barely flapping!")
}
}
class Penguin extends Bird {
useWings() {
console.log("Diving!")
}
}
var baldEagle = new Eagle();
var kingPenguin = new Penguin();
baldEagle.useWings(); // "Flying! Barely flapping!"
kingPenguin.useWings(); // "Diving!"
// more features example
class Train {
constructor(color, lightsOn) {
this.color = color;
this.lightsOn = lightsOn;
}
toggleLights() {
this.lightsOn = !this.lightsOn;
}
lightsStatus() {
console.log('Lights on?', this.lightsOn);
}
getSelf() {
console.log(this);
}
getPrototype() {
var proto = Object.getPrototypeOf(this);
console.log(proto);
}
}
class HighSpeedTrain extends Train {
constructor(passengers, highSpeedOn, color, lightsOn) {
super(color, lightsOn);
this.passengers = passengers;
this.highSpeedOn = highSpeedOn;
}
toggleHighSpeed() {
this.highSpeedOn = !this.highSpeedOn;
console.log('High speed status:', this.highSpeedOn);
}
toggleLights() {
super.toggleLights();
super.lightsStatus();
console.log('Lights are 100% operational.');
}
}
var myFirstTrain = new Train('red', false);
console.log(myFirstTrain); // Train {color: 'red', lightsOn: false}
var mySecondTrain = new Train('blue', false);
var myThirdTrain = new Train('blue', false);
var train4 = new Train('red', false);
train4.toggleLights(); // undefined
train4.lightsStatus(); // Lights on? true
train4.getSelf(); // Train {color: 'red', lightsOn: true}
train4.getPrototype(); // {constructor: f, toggleLights: f, ligthsStatus: f, getSelf: f, getPrototype: f}
var train5 = new Train('blue', false);
var highSpeed1 = new HighSpeedTrain(200, false, 'green', false);
train5.toggleLights(); // undefined
train5.lightsStatus(); // Lights on? true
highSpeed1.toggleLights(); // Lights on? true, Lights are 100% operational.
// using class instance as another class' constructor's property
class StationaryBike {
constructor(position, gears) {
this.position = position
this.gears = gears
}
}
class Treadmill {
constructor(position, modes) {
this.position = position
this.modes = modes
}
}
class Gym {
constructor(openHrs, stationaryBikePos, treadmillPos) {
this.openHrs = openHrs
this.stationaryBike = new StationaryBike(stationaryBikePos, 8)
this.treadmill = new Treadmill(treadmillPos, 5)
}
}
var boxingGym = new Gym("7-22", "right corner", "left corner")
console.log(boxingGym.openHrs)
console.log(boxingGym.stationaryBike)
console.log(boxingGym.treadmill)
/* designing an OOP
essential keywords: extends and super
1. thinking of the inheritance hierarchy I want to build
2. code the structure of the hierarchy (namely the base class and the sub-class place)
3. ask the following questions: what should go into the base class? what will all the sub-classes inherit?
what are the specific properties and methods that separate each class from others? how will the classes relate to one another?
4. add all the requirements as comments inside the code structure
5. start coding each class as per the specifications added as comments
6. after that, build various objects for the sub-classes
*/
class Animal {
constructor(color = 'yellow', energy = 100) {
this.color = color;
this.energy = energy;
}
isActive() {
if(this.energy > 0) {
this.energy -= 20;
console.log('Energy is decreasing, currently at:', this.energy)
} else if(this.energy == 0){
this.sleep();
}
}
sleep() {
this.energy += 20;
console.log('Energy is increasing, currently at:', this.energy)
}
getColor() {
console.log(this.color)
}
}
class Cat extends Animal {
constructor(sound = 'purr', canJumpHigh = true, canClimbTrees = true, color, energy) {
super(color, energy);
this.sound = sound;
this.canClimbTrees = canClimbTrees;
this.canJumpHigh = canJumpHigh;
}
makeSound() {
console.log(this.sound);
}
}
class Bird extends Animal {
constructor(sound = 'chirp', canFly = true, color, energy) {
super(color, energy);
this.sound = sound;
this.canFly = canFly;
}
makeSound() {
console.log(this.sound);
}
}
class HouseCat extends Cat {
constructor(houseCatSound = "meow", sound,canJumpHigh,canClimbTrees, color,energy) {
super(sound,canJumpHigh,canClimbTrees, color,energy);
this.houseCatSound = houseCatSound;
}
makeSound(option) {
if (option) {
super.makeSound();
}
console.log(this.houseCatSound);
}
}
class Tiger extends Cat {
constructor(tigerSound = "Roar!", sound,canJumpHigh,canClimbTrees, color,energy) {
super(sound,canJumpHigh,canClimbTrees, color,energy);
this.tigerSound = tigerSound;
}
makeSound(option) {
if (option) {
super.makeSound();
}
console.log(this.tigerSound);
}
}
class Parrot extends Bird {
constructor(canTalk = false, sound,canFly, color,energy) {
super(sound,canFly, color,energy);
this.canTalk = canTalk;
}
makeSound(option) {
if (option) {
super.makeSound();
}
if (this.canTalk) {
console.log("I'm a talking parrot!");
}
}
}
var fiji = new Parrot(false); // we're passing `false` to the constructor so that fiji can't talk
var polly = new Parrot(true); // we're passing `true` to the constructor so that polly can talk
fiji.makeSound(); // undefined
fiji.makeSound(true); // chirp
polly.makeSound(); // I'm a talking parrot!
polly.makeSound(true); // chirp, I'm a talking parrot!
polly.color; // yellow
polly.energy; // 100
polly.isActive(); // Energy is decreasing, currently at: 80
var penguin = new Bird("shriek", false, "black and white", 200); // setting all the custom properties
penguin; // Bird {color: 'black and white', energy: 200, sound: 'shriek', canFly: false }
penguin.sound; // 'shriek'
penguin.canFly; // false
penguin.color; // 'black and white'
penguin.energy; // 200
penguin.isActive(); // Energy is decreasing, currently at: 180
var leo = new HouseCat();
// leo, no purring please:
leo.makeSound(false); // meow
// leo, both purr and meow now:
leo.makeSound(true); // purr, meow
var cuddles = new Tiger();
cuddles.makeSound(false); // Roar!
cuddles.makeSound(true); // purr, Roar!
// default parameters
class WithDefaultParams {
constructor(num1 = 1, num2 = 2, num3 = 3, string1 = "Result:", bool1 = true) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
this.string1 = string1;
this.bool1 = bool1;
}
calculate() {
if(this.bool1) {
console.log(this.string1, this.num1 + this.num2 + this.num3);
return;
}
return "The value of bool1 is incorrect"
}
}
var better = new WithDefaultParams();
better.calculate(); // Result: 6
// template literals
let greet = "Hello";
let place = "World";
console.log(`${greet} ${place} !`) // it allows for variable interpolation
// // multiline strings
let multiline = `
This is a multiline string,
possible in ES6!
`;
console.log (multiline);
// expression evaluation
console.log(`${1 + 1 + 1 + 1 + 1} stars!`)