-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
executable file
·699 lines (585 loc) · 18.4 KB
/
script.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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
'use strict';
/*
//Constructor Functions
//function expression
const Person = function (firstName, birthYear) {
// console.log(this); //Person {}
//instance properties
this.firstName = firstName;
this.birthYear = birthYear;
// This could work, but it is bad practice, you should never create method inside constructor functions.
// this.calcAge = function () {
// console.log(2037 - this.birthYear);
// };
};
const benson = new Person('Benson', 2000);
console.log(benson); //Person {firstName: 'benson', birthYear: 2000}
// What happens when we call a function with the new operator
//1. New empty object is created
//2. The function is called, then the this keyword is set to the new empty object.
//3. The Newly created object is linked to prototype
//4. Function auto returns the object created from the beginning.
const makau = new Person('Makau', 2002);
const ruth = new Person('Ruth', 2002);
console.log(ruth, makau);
//`Person {firstName: 'Ruth', birthYear: 2002} Person {firstName: 'Makau', birthYear: 2002}`;
console.log(benson instanceof Person); //true
//Prototypes
console.log(Person.prototype);
Person.prototype.calcAge = function () {
console.log(2037 - this.birthYear);
};
benson.calcAge(); //37
ruth.calcAge(); //35
//Prototype for benson
console.log(benson.__proto__); //{calcAge: ƒ, constructor: ƒ}
console.log(benson.__proto__ === Person.prototype); //true
console.log(Person.prototype.isPrototypeOf(benson)); //true
console.log(Person.prototype.isPrototypeOf(Person)); //false
//setting properties in the Person.prototype
Person.prototype.species = 'Homo Sapiens';
console.log(benson);
console.log(ruth);
console.log(makau);
console.log(benson.species); //Homo Sapiens
console.log(ruth.species); //Homo Sapiens
console.log(benson.hasOwnProperty('firstName')); //true
console.log(benson.hasOwnProperty('species')); //false
console.log(benson.__proto__);
console.log(benson.__proto__.__proto__);
console.log(benson.__proto__.__proto__.__proto__);
console.dir(Person.prototype.constructor);
//Prototype of Arrays
const arr = [3, 6, 4, 6, 9, 5, 6, 9, 3];
console.log(arr.__proto__); // Returns all functions that exists in Array.prototype
console.log(arr.__proto__ === Array.prototype); //true
Array.prototype.unique = function () {
return [...new Set(this)];
};
console.log(arr.unique()); //[3, 6, 4, 9, 5]
const h1 = document.querySelector('h1');
console.dir(h1);
///////////////////////////////////////
// Coding Challenge #1
/*
1. Use a constructor function to implement a Car. A car has a make and a speed property.
The speed property is the current speed of the car in km/h;
2. Implement an 'accelerate' method that will increase the car's speed by 10, and log the new speed to the console;
3. Implement a 'brake' method that will decrease the car's speed by 5, and log the new speed to the console;
4. Create 2 car objects and experiment with calling 'accelerate' and 'brake' multiple times on each of them.
DATA CAR 1: 'BMW' going at 120 km/h
DATA CAR 2: 'Mercedes' going at 95 km/h
GOOD LUCK 😀
//constructor function
const Car = function (make, speed) {
this.speed = speed;
this.make = make;
};
//create functions
Car.prototype.accelerate = function () {
this.speed += 10;
console.log(`${this.make} is going at ${this.speed}`);
};
Car.prototype.break = function () {
this.speed -= 15;
console.log(`${this.make} is going at ${this.speed}`);
};
//create car objects
const bmw = new Car('BMW', 120);
const mercedes = new Car('Mercedes', 93);
bmw.accelerate();
bmw.break();
bmw.accelerate();
bmw.accelerate();
bmw.break();
bmw.break();
bmw.break();
bmw.accelerate();
bmw.accelerate();
bmw.break();
bmw.accelerate();
//ES6 CLASSES
//class expression
// const PersonCL = class {};
//Class Declaration
class PersonCl {
//add constructor method- works as constructor function.
constructor(firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
}
//Properties and Methods writted outside constructor will be in prototype
calcAge() {
console.log(2037 - this.birthYear);
}
}
//create object (Instance)
const jessica = new PersonCl('Jesicca Brown', 1998);
console.log(jessica);
jessica.calcAge(); //39
console.log(jessica.__proto__ === PersonCl.prototype); //true
PersonCl.prototype.greet = function () {
console.log(`Hey ${this.firstName}`);
};
jessica.greet(); //Hey Jesicca Brown
const account = {
owner: 'Jonas',
movements: [200, 530, 120, 300],
//getter - To make a method a getter, you prepend the keyword get before the method
get latest() {
return this.movements.slice(-1).pop();
},
//setter- to make a method a setter, prepend the keyword set before the method
set latest(mov) {
//setter must always have at least one method parameter
this.movements.push(mov);
},
};
//to access the getter, we call it like a property not method
console.log(account.latest); //300
account.latest = 50;
console.log(account.movements);
//Getters and Setters in Classes
class PersonCl {
//add constructor method- works as constructor function.
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
//Properties and Methods writted outside constructor will be in prototype
calcAge() {
console.log(2037 - this.birthYear);
}
//getter in a class
get age() {
return 2037 - this.birthYear;
}
//setting a property that already exists
set fullName(name) {
console.log(name);
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name`);
}
get fullName() {
return this._fullName;
}
}
const bensonCl = new PersonCl('Benson Makau', 2000);
console.log(bensonCl.age); //37
const walter = new PersonCl('Walter Kivyolo', 1995);
//static methods
const Person = function (firstName, birthYear) {
// console.log(this); //Person {}
//instance properties
this.firstName = firstName;
this.birthYear = birthYear;
// This could work, but it is bad practice, you should never create method inside constructor functions.
// this.calcAge = function () {
// console.log(2037 - this.birthYear);
// };
};
const ruth = new Person('Ruth', 2002);
const makau = new Person('Makau', 2000);
console.log(ruth, makau);
//creating a static method
Person.hey = function () {
console.log('Hey There.....!!!');
};
//calling the function
Person.hey();
//Objects Cant Access The Method Above
// makau.hey();
//Uncaught TypeError: makau.hey is not a function
//This is because, the function is not defined in the constructor functions prototype.
class PersonCl {
//add constructor method- works as constructor function.
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
//INSTANCE METHODS
//Properties and Methods writted outside constructor will be in prototype
calcAge() {
console.log(2037 - this.birthYear);
}
//getter in a class
get age() {
return 2037 - this.birthYear;
}
//setting a property that already exists
set fullName(name) {
console.log(name);
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name`);
}
get fullName() {
return this._fullName;
}
//creating static method
static hey() {
console.log('Hey There.....!CLASSS!');
}
}
const bensonCl = new PersonCl('Benson Makau', 2000);
console.log(bensonCl.age); //37
PersonCl.hey();
//Object.create
const personProto = {
calcAge() {
console.log(2037 - this.birthYear);
},
init(firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
},
};
//This object will be the prototype of all the Person objects
const steven = Object.create(personProto);
console.log(steven);
steven.name = 'Steven';
steven.birthYear = 2001;
steven.calcAge(); //36
console.log(steven.__proto__ === personProto); //true
const sarah = Object.create(personProto);
sarah.init('Sarah', 1979);
sarah.calcAge();
///////////////////////////////////////
// Coding Challenge #2
/*
1. Re-create challenge 1, but this time using an ES6 class;
2. Add a getter called 'speedUS' which returns the current speed in mi/h (divide by 1.6);
3. Add a setter called 'speedUS' which sets the current speed in mi/h (but converts it to km/h before storing the value, by multiplying the input by 1.6);
4. Create a new car and experiment with the accelerate and brake methods, and with the getter and setter.
DATA CAR 1: 'Ford' going at 120 km/h
GOOD LUCK 😀
//constructor function
class CarCl {
constructor(make, speed) {
this.speed = speed;
this.make = make;
}
//create functions
accelerate() {
this.speed += 10;
console.log(`${this.make} is going at ${this.speed}`);
}
break() {
this.speed -= 15;
console.log(`${this.make} is going at ${this.speed} km/h`);
}
get speedUS() {
return this.speed / 1.6;
}
set speedUS(speed) {
this.speed = speed * 1.6;
}
}
const ford = new CarCl('Ford', 120);
console.log(ford.speedUS);
ford.accelerate();
ford.accelerate();
ford.break();
ford.speedUS = 50;
console.log(ford);
//Inheritance Between Classes : Constructor Functions
const Person = function (firstName, birthYear) {
// console.log(this); //Person {}
//instance properties
this.firstName = firstName;
this.birthYear = birthYear;
};
Person.prototype.calcAge = function () {
console.log(2037 - this.birthYear);
};
//Child Class - Pass all the args in parent class plus its own additional ones.
const Student = function (firstName, birthYear, course) {
//method 1: VIOLATES DRY PRINCIPLE
// this.firstName = firstName;
// this.birthYear = birthYear;
//METHOD 2
Person.call(this, firstName, birthYear);
this.course = course;
};
//Linking Prototypes
Student.prototype = Object.create(Person.prototype);
// Student.prototype is now an object that inherits from Person.prototype
Student.prototype.introduce = function () {
console.log(`My name is ${this.firstName} and I am studying ${this.course}`);
};
const mike = new Student('Mike', 2020, 'Computer Science');
console.log(mike);
mike.introduce();
mike.calcAge();
Student.prototype.constructor = Student;
console.log(Student.prototype.constructor);
*/
///////////////////////////////////////
// Coding Challenge #3
/*
1. Use a constructor function to implement an Electric Car (called EV) as a CHILD "class" of Car. Besides a make and current speed, the EV also has the current battery charge in % ('charge' property);
2. Implement a 'chargeBattery' method which takes an argument 'chargeTo' and sets the battery charge to 'chargeTo';
3. Implement an 'accelerate' method that will increase the car's speed by 20, and decrease the charge by 1%. Then log a message like this: 'Tesla going at 140 km/h, with a charge of 22%';
4. Create an electric car object and experiment with calling 'accelerate', 'brake' and 'chargeBattery' (charge to 90%). Notice what happens when you 'accelerate'! HINT: Review the definiton of polymorphism 😉
DATA CAR 1: 'Tesla' going at 120 km/h, with a charge of 23%
GOOD
//constructor function
const Car = function (make, speed) {
this.speed = speed;
this.make = make;
};
//create functions
Car.prototype.accelerate = function () {
this.speed += 10;
console.log(`${this.make} is going at ${this.speed}`);
};
Car.prototype.break = function () {
this.speed -= 5;
console.log(`${this.make} is going at ${this.speed} km/h`);
};
const EV = function (make, speed, charge) {
Car.call(this, make, speed); //inheriting parent class
this.charge = charge;
};
//Link the prototypes
EV.prototype = Object.create(Car.prototype);
EV.prototype.chargeBattery = function (chargeTo) {
this.charge = chargeTo;
};
EV.prototype.accelerate = function () {
this.speed += 20;
this.charge--;
console.log(
`${this.make} is going at ${this.speed} km/h with a charge of ${this.charge}`
);
};
//Create EV Object
const tesla = new EV('Tesla', 120, 23);
tesla.chargeBattery(90);
// console.log(tesla);
// tesla.break();
// tesla.accelerate();
//Inheritance Between Classes: ES6 CLASSES
//Static Method
class PersonCl {
//add constructor method- works as constructor function.
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
//Properties and Methods writted outside constructor will be in prototype
calcAge() {
console.log(2037 - this.birthYear);
}
greet() {
console.log(`Hey ${this.fullName}`);
}
//getter in a class
get age() {
return 2037 - this.birthYear;
}
//setting a property that already exists
set fullName(name) {
// console.log(name);
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name`);
}
get fullName() {
return this._fullName;
}
//static method
static hey() {
console.log('Hey There!!');
}
}
//linking prototypes
class StudentCl extends PersonCl {
constructor(fullName, birthYear, course) {
//Always needs to happen first
super(fullName, birthYear); //Constructor of the Parent Class
this.course = course;
}
introduce() {
console.log(`My name is ${this.fullName} and I study ${this.course}`);
}
//Overriding The Original calcAge() function
calcAge() {
console.log(
`I am ${2037 - this.birthYear} years old, but as a student i feel like ${
2037 - this.birthYear + 10
}`
);
}
}
const martha = new StudentCl('Martha James', 2012, 'Computer Science');
// console.log(martha);
// martha.introduce();
// martha.calcAge();
//INHERITANCE BETWEEN CLASSES: OBJECT.CREATE
//Object.create
const personProto = {
calcAge() {
console.log(2037 - this.birthYear);
},
init(firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
},
};
//This object will be the prototype of all the Person objects
const steven = Object.create(personProto);
//linking prototypes
const studentProto = Object.create(personProto);
studentProto.init = function (firstName, birthYear, course) {
personProto.init.call(this, firstName, birthYear);
this.course = course;
};
studentProto.introduce = function () {
console.log(`My name is ${this.fullName} and I study ${this.course}`);
};
const jay = Object.create(studentProto);
jay.init('Jay', 2010, 'Computer Science');
jay.introduce();
jay.calcAge();
//ENCAPSULATION: PROTECTED PROPERTIES AND METHODS
//Public fields
//Private fields
//Public Methods
//Private Methods
class Account {
//defining a public fields(always will be on every instance created)
//These fields are also referencable with the this keyword
locale = navigator.language;
//private fields syntax
#movements = [];
#pin;
constructor(owner, currency, pin) {
this.owner = owner;
this.currency = currency;
this.#pin = pin;
//protected property
// this._movements = [];
// this.locale = navigator.language;
console.log(`Thanks for choosing to Bank with Us,${owner} `);
}
//PUBLIC INTERFACE(API)
getPin() {
return this._pin;
}
getMovements() {
return this.#movements;
}
deposit(val) {
this.#movements.push(val);
return this;
}
withdraw(val) {
this.deposit(-val);
}
//Protected Methods
_approveLoan(val) {
return true;
}
requestLoan(val) {
if (this._approveLoan(val)) {
this.deposit(val);
console.log(`Loan amount of ${val} has been approved. `);
return this;
}
}
// requestLoan(val) {
// if (this.#approveLoan(val)) {
// this.deposit(val);
// console.log(`Loan amount of ${val} has been approved. `);
// }
// }
// //Private Methods
// #approveLoan(val) {
// return true;
// }
//static methods
static helper() {
console.log('Helper');
}
}
const acc1 = new Account('Benson', 'KSH', 1111);
//WAY 1
// acc1._movements.push(250);
// acc1._movements.push(-140);
//WAY 2
acc1.deposit(250);
acc1.withdraw(140);
acc1.requestLoan(1000);
// console.log(acc1);
//correct way to get ,ovements : since you can change them.
console.log(acc1.getPin());
console.log(acc1.getMovements());
console.log(acc1);
Account.helper();
// console.log(acc1.#movements); //Private field '#movements' must be declared in an enclosing class
// console.log(acc1.#pin); // Private field '#pin' must be declared in an enclosing class
//chaining
acc1.deposit(300).deposit(500).withdraw(35).requestLoan(25000).withdraw(4000);
console.log(acc1.getMovements());
///////////////////////////////////////
// Coding Challenge #4
1. Re-create challenge #3, but this time using ES6 classes: create an 'EVCl' child class of the 'CarCl' class
2. Make the 'charge' property private;
3. Implement the ability to chain the 'accelerate' and 'chargeBattery' methods of this class, and also update the 'brake' method in the 'CarCl' class. They experiment with chining!
DATA CAR 1: 'Rivian' going at 120 km/h, with a charge of 23%
GOOD LUCK 😀
*/
class CarCl {
constructor(make, speed) {
this.speed = speed;
this.make = make;
}
//create functions
accelerate() {
this.speed += 10;
console.log(`${this.make} is going at ${this.speed}`);
return this;
}
break() {
this.speed -= 15;
console.log(`${this.make} is going at ${this.speed} km/h`);
return this;
}
get speedUS() {
return this.speed / 1.6;
}
set speedUS(speed) {
this.speed = speed * 1.6;
}
}
class EVCl extends CarCl {
#charge;
constructor(make, speed, charge) {
super(make, speed); //inheriting parent class
this.#charge = charge;
}
chargeBattery(chargeTo) {
this.#charge = chargeTo;
return this;
}
accelerate() {
this.speed += 20;
this.#charge--;
console.log(
`${this.make} is going at ${this.speed} km/h with a charge of ${
this.#charge
}`
);
return this;
}
}
const rivian = new EVCl('Rivian', 128, 23);
console.log(rivian);
//chaining methods
rivian
.accelerate()
.accelerate()
.accelerate()
.break()
.chargeBattery(50)
.accelerate();
console.log(rivian.speedUS);