-
Notifications
You must be signed in to change notification settings - Fork 0
/
03_javascript_class_examples.html
871 lines (851 loc) · 82.1 KB
/
03_javascript_class_examples.html
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.5.45">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>javascript_class_examples</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { display: inline-block; text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="03_javascript_class_examples_files/libs/clipboard/clipboard.min.js"></script>
<script src="03_javascript_class_examples_files/libs/quarto-html/quarto.js"></script>
<script src="03_javascript_class_examples_files/libs/quarto-html/popper.min.js"></script>
<script src="03_javascript_class_examples_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="03_javascript_class_examples_files/libs/quarto-html/anchor.min.js"></script>
<link href="03_javascript_class_examples_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="03_javascript_class_examples_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="03_javascript_class_examples_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="03_javascript_class_examples_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="03_javascript_class_examples_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
</head>
<body class="fullcontent">
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<main class="content" id="quarto-document-content">
<p>Below are examples of JavaScript classes with business case examples.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode javascript code-with-copy"><code class="sourceCode javascript"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">// Class for Menu Items</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> MenuItem {</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> <span class="co">// Constructor to initialize the name and price of a menu item</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> <span class="fu">constructor</span>(name<span class="op">,</span> price) {</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">name</span> <span class="op">=</span> name<span class="op">;</span> <span class="co">// The name of the menu item (e.g., "Burger")</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">price</span> <span class="op">=</span> price<span class="op">;</span> <span class="co">// The price of the menu item (e.g., 10.99)</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="co">// Class for Orders</span></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> Order {</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a> <span class="co">// Constructor to initialize an order with an ID and customer name</span></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a> <span class="fu">constructor</span>(orderId<span class="op">,</span> customerName) {</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">orderId</span> <span class="op">=</span> orderId<span class="op">;</span> <span class="co">// Unique ID for the order (e.g., 101)</span></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">customerName</span> <span class="op">=</span> customerName<span class="op">;</span> <span class="co">// Name of the customer placing the order (e.g., "John Doe")</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">items</span> <span class="op">=</span> []<span class="op">;</span> <span class="co">// Initialize an empty array to store ordered items</span></span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">totalAmount</span> <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> <span class="co">// Initialize totalAmount to 0, to be calculated as items are added</span></span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to add an item to the order</span></span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a> <span class="fu">addItem</span>(menuItem) {</span>
<span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">items</span><span class="op">.</span><span class="fu">push</span>(menuItem)<span class="op">;</span> <span class="co">// Add the menu item to the order's item list</span></span>
<span id="cb1-23"><a href="#cb1-23" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">totalAmount</span> <span class="op">+=</span> menuItem<span class="op">.</span><span class="at">price</span><span class="op">;</span> <span class="co">// Update the total amount by adding the price of the item</span></span>
<span id="cb1-24"><a href="#cb1-24" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb1-25"><a href="#cb1-25" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-26"><a href="#cb1-26" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to apply a discount to the total amount</span></span>
<span id="cb1-27"><a href="#cb1-27" aria-hidden="true" tabindex="-1"></a> <span class="fu">applyDiscount</span>(discountAmount) {</span>
<span id="cb1-28"><a href="#cb1-28" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">totalAmount</span> <span class="op">-=</span> discountAmount<span class="op">;</span> <span class="co">// Subtract the discount amount from the total amount</span></span>
<span id="cb1-29"><a href="#cb1-29" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb1-30"><a href="#cb1-30" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-31"><a href="#cb1-31" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to calculate the final total amount</span></span>
<span id="cb1-32"><a href="#cb1-32" aria-hidden="true" tabindex="-1"></a> <span class="fu">calculateTotal</span>() {</span>
<span id="cb1-33"><a href="#cb1-33" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">this</span><span class="op">.</span><span class="at">totalAmount</span><span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="op">;</span> <span class="co">// Return the total amount as a string, fixed to two decimal places (e.g., "15.99")</span></span>
<span id="cb1-34"><a href="#cb1-34" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb1-35"><a href="#cb1-35" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-36"><a href="#cb1-36" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to print the details of the order</span></span>
<span id="cb1-37"><a href="#cb1-37" aria-hidden="true" tabindex="-1"></a> <span class="fu">printOrder</span>() {</span>
<span id="cb1-38"><a href="#cb1-38" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Order ID: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">orderId</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span> <span class="co">// Print the order ID</span></span>
<span id="cb1-39"><a href="#cb1-39" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Customer: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span> <span class="co">// Print the customer name</span></span>
<span id="cb1-40"><a href="#cb1-40" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Items Ordered:"</span>)<span class="op">;</span> <span class="co">// Print a heading for the list of ordered items</span></span>
<span id="cb1-41"><a href="#cb1-41" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">items</span><span class="op">.</span><span class="fu">forEach</span>(item <span class="kw">=></span> {</span>
<span id="cb1-42"><a href="#cb1-42" aria-hidden="true" tabindex="-1"></a> <span class="co">// For each item in the order, print its name and price</span></span>
<span id="cb1-43"><a href="#cb1-43" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`- </span><span class="sc">${</span>item<span class="op">.</span><span class="at">name</span><span class="sc">}</span><span class="vs">: $</span><span class="sc">${</span>item<span class="op">.</span><span class="at">price</span><span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb1-44"><a href="#cb1-44" aria-hidden="true" tabindex="-1"></a> })<span class="op">;</span></span>
<span id="cb1-45"><a href="#cb1-45" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Total Amount: $</span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="fu">calculateTotal</span>()<span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span> <span class="co">// Print the total amount after adding all items and applying any discounts</span></span>
<span id="cb1-46"><a href="#cb1-46" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb1-47"><a href="#cb1-47" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb1-48"><a href="#cb1-48" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-49"><a href="#cb1-49" aria-hidden="true" tabindex="-1"></a><span class="co">// Example usage:</span></span>
<span id="cb1-50"><a href="#cb1-50" aria-hidden="true" tabindex="-1"></a><span class="co">// Create new menu items</span></span>
<span id="cb1-51"><a href="#cb1-51" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> item1 <span class="op">=</span> <span class="kw">new</span> <span class="fu">MenuItem</span>(<span class="st">"Burger"</span><span class="op">,</span> <span class="fl">10.99</span>)<span class="op">;</span> <span class="co">// Create a menu item named "Burger" priced at $10.99</span></span>
<span id="cb1-52"><a href="#cb1-52" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> item2 <span class="op">=</span> <span class="kw">new</span> <span class="fu">MenuItem</span>(<span class="st">"Fries"</span><span class="op">,</span> <span class="fl">3.49</span>)<span class="op">;</span> <span class="co">// Create a menu item named "Fries" priced at $3.49</span></span>
<span id="cb1-53"><a href="#cb1-53" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> item3 <span class="op">=</span> <span class="kw">new</span> <span class="fu">MenuItem</span>(<span class="st">"Soda"</span><span class="op">,</span> <span class="fl">1.99</span>)<span class="op">;</span> <span class="co">// Create a menu item named "Soda" priced at $1.99</span></span>
<span id="cb1-54"><a href="#cb1-54" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-55"><a href="#cb1-55" aria-hidden="true" tabindex="-1"></a><span class="co">// Create a new order</span></span>
<span id="cb1-56"><a href="#cb1-56" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> order1 <span class="op">=</span> <span class="kw">new</span> <span class="fu">Order</span>(<span class="dv">101</span><span class="op">,</span> <span class="st">"John Doe"</span>)<span class="op">;</span> <span class="co">// Create a new order with ID 101 for customer "John Doe"</span></span>
<span id="cb1-57"><a href="#cb1-57" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-58"><a href="#cb1-58" aria-hidden="true" tabindex="-1"></a><span class="co">// Add items to the order</span></span>
<span id="cb1-59"><a href="#cb1-59" aria-hidden="true" tabindex="-1"></a>order1<span class="op">.</span><span class="fu">addItem</span>(item1)<span class="op">;</span> <span class="co">// Add the "Burger" item to the order</span></span>
<span id="cb1-60"><a href="#cb1-60" aria-hidden="true" tabindex="-1"></a>order1<span class="op">.</span><span class="fu">addItem</span>(item2)<span class="op">;</span> <span class="co">// Add the "Fries" item to the order</span></span>
<span id="cb1-61"><a href="#cb1-61" aria-hidden="true" tabindex="-1"></a>order1<span class="op">.</span><span class="fu">addItem</span>(item3)<span class="op">;</span> <span class="co">// Add the "Soda" item to the order</span></span>
<span id="cb1-62"><a href="#cb1-62" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-63"><a href="#cb1-63" aria-hidden="true" tabindex="-1"></a><span class="co">// Apply a discount to the order</span></span>
<span id="cb1-64"><a href="#cb1-64" aria-hidden="true" tabindex="-1"></a>order1<span class="op">.</span><span class="fu">applyDiscount</span>(<span class="fl">2.00</span>)<span class="op">;</span> <span class="co">// Apply a discount of $2.00 to the total amount</span></span>
<span id="cb1-65"><a href="#cb1-65" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-66"><a href="#cb1-66" aria-hidden="true" tabindex="-1"></a><span class="co">// Print the order details to the console</span></span>
<span id="cb1-67"><a href="#cb1-67" aria-hidden="true" tabindex="-1"></a>order1<span class="op">.</span><span class="fu">printOrder</span>()<span class="op">;</span> <span class="co">// Print the order information, including items, customer name, and total amount</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">Summary:</h3>
<ul>
<li>The <code>MenuItem</code> class holds individual items like “Burger” and “Fries” with their prices.</li>
<li>The <code>Order</code> class manages an order by storing customer information, items, and the total cost. It has methods to add items, apply discounts, and print the order details.</li>
<li>The final section creates menu items, adds them to an order, applies a discount, and prints the order summary to the console.</li>
</ul>
<p>Here’s an example using JavaScript classes with getters and setters in a business case where we manage a subscription service for customers. The subscription plan includes the customer’s details, their plan, and whether or not their subscription is active.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode javascript code-with-copy"><code class="sourceCode javascript"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="co">// Class representing a Subscription</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> Subscription {</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">constructor</span>(customerName<span class="op">,</span> plan) {</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">customerName</span> <span class="op">=</span> customerName<span class="op">;</span> <span class="co">// The name of the customer</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">_plan</span> <span class="op">=</span> plan<span class="op">;</span> <span class="co">// Subscription plan (e.g., "Basic", "Premium")</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">_isActive</span> <span class="op">=</span> <span class="kw">false</span><span class="op">;</span> <span class="co">// Subscription is initially inactive</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a> <span class="co">// Getter for the subscription plan</span></span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a> <span class="kw">get</span> <span class="fu">plan</span>() {</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">this</span><span class="op">.</span><span class="at">_plan</span><span class="op">;</span> <span class="co">// Return the current subscription plan</span></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a> <span class="co">// Setter for the subscription plan</span></span>
<span id="cb2-15"><a href="#cb2-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">set</span> <span class="fu">plan</span>(newPlan) {</span>
<span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (newPlan <span class="op">===</span> <span class="st">"Basic"</span> <span class="op">||</span> newPlan <span class="op">===</span> <span class="st">"Premium"</span> <span class="op">||</span> newPlan <span class="op">===</span> <span class="st">"VIP"</span>) {</span>
<span id="cb2-17"><a href="#cb2-17" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">_plan</span> <span class="op">=</span> newPlan<span class="op">;</span> <span class="co">// Update the plan if it's one of the valid options</span></span>
<span id="cb2-18"><a href="#cb2-18" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb2-19"><a href="#cb2-19" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Invalid plan selected. Choose either 'Basic', 'Premium', or 'VIP'."</span>)<span class="op">;</span></span>
<span id="cb2-20"><a href="#cb2-20" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-21"><a href="#cb2-21" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-22"><a href="#cb2-22" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-23"><a href="#cb2-23" aria-hidden="true" tabindex="-1"></a> <span class="co">// Getter for the subscription status</span></span>
<span id="cb2-24"><a href="#cb2-24" aria-hidden="true" tabindex="-1"></a> <span class="kw">get</span> <span class="fu">isActive</span>() {</span>
<span id="cb2-25"><a href="#cb2-25" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">this</span><span class="op">.</span><span class="at">_isActive</span><span class="op">;</span> <span class="co">// Return whether the subscription is active</span></span>
<span id="cb2-26"><a href="#cb2-26" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-27"><a href="#cb2-27" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-28"><a href="#cb2-28" aria-hidden="true" tabindex="-1"></a> <span class="co">// Setter for the subscription status</span></span>
<span id="cb2-29"><a href="#cb2-29" aria-hidden="true" tabindex="-1"></a> <span class="kw">set</span> <span class="fu">isActive</span>(status) {</span>
<span id="cb2-30"><a href="#cb2-30" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (<span class="kw">typeof</span> status <span class="op">===</span> <span class="st">'boolean'</span>) {</span>
<span id="cb2-31"><a href="#cb2-31" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">_isActive</span> <span class="op">=</span> status<span class="op">;</span> <span class="co">// Set the active status if a boolean is passed</span></span>
<span id="cb2-32"><a href="#cb2-32" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb2-33"><a href="#cb2-33" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Invalid status. Must be true or false."</span>)<span class="op">;</span></span>
<span id="cb2-34"><a href="#cb2-34" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-35"><a href="#cb2-35" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-36"><a href="#cb2-36" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-37"><a href="#cb2-37" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to display the subscription details</span></span>
<span id="cb2-38"><a href="#cb2-38" aria-hidden="true" tabindex="-1"></a> <span class="fu">displaySubscription</span>() {</span>
<span id="cb2-39"><a href="#cb2-39" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Customer: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb2-40"><a href="#cb2-40" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Plan: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">plan</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb2-41"><a href="#cb2-41" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Subscription Active: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">isActive</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb2-42"><a href="#cb2-42" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb2-43"><a href="#cb2-43" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb2-44"><a href="#cb2-44" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-45"><a href="#cb2-45" aria-hidden="true" tabindex="-1"></a><span class="co">// Example usage:</span></span>
<span id="cb2-46"><a href="#cb2-46" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-47"><a href="#cb2-47" aria-hidden="true" tabindex="-1"></a><span class="co">// Create a new subscription for a customer</span></span>
<span id="cb2-48"><a href="#cb2-48" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> customerSubscription <span class="op">=</span> <span class="kw">new</span> <span class="fu">Subscription</span>(<span class="st">"Alice Smith"</span><span class="op">,</span> <span class="st">"Basic"</span>)<span class="op">;</span></span>
<span id="cb2-49"><a href="#cb2-49" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-50"><a href="#cb2-50" aria-hidden="true" tabindex="-1"></a><span class="co">// Access the plan using the getter</span></span>
<span id="cb2-51"><a href="#cb2-51" aria-hidden="true" tabindex="-1"></a><span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(customerSubscription<span class="op">.</span><span class="at">plan</span>)<span class="op">;</span> <span class="co">// Outputs: "Basic"</span></span>
<span id="cb2-52"><a href="#cb2-52" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-53"><a href="#cb2-53" aria-hidden="true" tabindex="-1"></a><span class="co">// Update the plan using the setter</span></span>
<span id="cb2-54"><a href="#cb2-54" aria-hidden="true" tabindex="-1"></a>customerSubscription<span class="op">.</span><span class="at">plan</span> <span class="op">=</span> <span class="st">"Premium"</span><span class="op">;</span> <span class="co">// Changes the plan to "Premium"</span></span>
<span id="cb2-55"><a href="#cb2-55" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-56"><a href="#cb2-56" aria-hidden="true" tabindex="-1"></a><span class="co">// Access the subscription status using the getter</span></span>
<span id="cb2-57"><a href="#cb2-57" aria-hidden="true" tabindex="-1"></a><span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(customerSubscription<span class="op">.</span><span class="at">isActive</span>)<span class="op">;</span> <span class="co">// Outputs: false (since it's inactive initially)</span></span>
<span id="cb2-58"><a href="#cb2-58" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-59"><a href="#cb2-59" aria-hidden="true" tabindex="-1"></a><span class="co">// Activate the subscription using the setter</span></span>
<span id="cb2-60"><a href="#cb2-60" aria-hidden="true" tabindex="-1"></a>customerSubscription<span class="op">.</span><span class="at">isActive</span> <span class="op">=</span> <span class="kw">true</span><span class="op">;</span> <span class="co">// Activates the subscription</span></span>
<span id="cb2-61"><a href="#cb2-61" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-62"><a href="#cb2-62" aria-hidden="true" tabindex="-1"></a><span class="co">// Attempt to set an invalid plan</span></span>
<span id="cb2-63"><a href="#cb2-63" aria-hidden="true" tabindex="-1"></a>customerSubscription<span class="op">.</span><span class="at">plan</span> <span class="op">=</span> <span class="st">"Gold"</span><span class="op">;</span> <span class="co">// Outputs: "Invalid plan selected. Choose either 'Basic', 'Premium', or 'VIP'."</span></span>
<span id="cb2-64"><a href="#cb2-64" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-65"><a href="#cb2-65" aria-hidden="true" tabindex="-1"></a><span class="co">// Display the subscription details</span></span>
<span id="cb2-66"><a href="#cb2-66" aria-hidden="true" tabindex="-1"></a>customerSubscription<span class="op">.</span><span class="fu">displaySubscription</span>()<span class="op">;</span> <span class="co">// Outputs:</span></span>
<span id="cb2-67"><a href="#cb2-67" aria-hidden="true" tabindex="-1"></a><span class="co">// Customer: Alice Smith</span></span>
<span id="cb2-68"><a href="#cb2-68" aria-hidden="true" tabindex="-1"></a><span class="co">// Plan: Premium</span></span>
<span id="cb2-69"><a href="#cb2-69" aria-hidden="true" tabindex="-1"></a><span class="co">// Subscription Active: true</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</section>
<section id="explanation" class="level3">
<h3 class="anchored" data-anchor-id="explanation">Explanation:</h3>
<ul>
<li><strong>Getters</strong> and <strong>Setters</strong> are used to access and modify private fields (<code>_plan</code> and <code>_isActive</code>).</li>
<li>The getter <code>get plan()</code> allows us to retrieve the current subscription plan, and the setter <code>set plan()</code> validates input before updating the plan.</li>
<li>Similarly, <code>get isActive()</code> returns the current subscription status, and <code>set isActive()</code> ensures that only boolean values are accepted when updating the subscription status.</li>
<li>The <code>displaySubscription()</code> method prints the subscription details to the console.</li>
</ul>
<p>This pattern of using getters and setters helps ensure controlled access to the object’s properties and adds validation logic whenever changes are made.</p>
<p>In this example, we’ll use JavaScript’s private class fields (denoted by <code>#</code>) along with getters and setters to manage a customer loyalty program. This program will track a customer’s points, their tier (based on points), and whether they have VIP status. The private properties ensure that these values can only be modified or accessed through the defined methods, adding more control to the logic.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode javascript code-with-copy"><code class="sourceCode javascript"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="co">// Class representing a Customer Loyalty Program</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> LoyaltyProgram {</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a> <span class="co">// Private properties for points, tier, and VIP status</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a> #points<span class="op">;</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a> #tier<span class="op">;</span></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a> #isVIP<span class="op">;</span></span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a> <span class="fu">constructor</span>(customerName) {</span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">customerName</span> <span class="op">=</span> customerName<span class="op">;</span> <span class="co">// The name of the customer</span></span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">points</span> <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> <span class="co">// Points start at 0</span></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">tier</span> <span class="op">=</span> <span class="st">"Bronze"</span><span class="op">;</span> <span class="co">// Default tier is "Bronze"</span></span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">isVIP</span> <span class="op">=</span> <span class="kw">false</span><span class="op">;</span> <span class="co">// VIP status is initially false</span></span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-15"><a href="#cb3-15" aria-hidden="true" tabindex="-1"></a> <span class="co">// Getter for points</span></span>
<span id="cb3-16"><a href="#cb3-16" aria-hidden="true" tabindex="-1"></a> <span class="kw">get</span> <span class="fu">points</span>() {</span>
<span id="cb3-17"><a href="#cb3-17" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">this</span><span class="op">.</span>#<span class="at">points</span><span class="op">;</span></span>
<span id="cb3-18"><a href="#cb3-18" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-19"><a href="#cb3-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-20"><a href="#cb3-20" aria-hidden="true" tabindex="-1"></a> <span class="co">// Setter for points</span></span>
<span id="cb3-21"><a href="#cb3-21" aria-hidden="true" tabindex="-1"></a> <span class="kw">set</span> <span class="fu">points</span>(newPoints) {</span>
<span id="cb3-22"><a href="#cb3-22" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (newPoints <span class="op">>=</span> <span class="dv">0</span>) { <span class="co">// Points cannot be negative</span></span>
<span id="cb3-23"><a href="#cb3-23" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">points</span> <span class="op">=</span> newPoints<span class="op">;</span></span>
<span id="cb3-24"><a href="#cb3-24" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="fu">updateTier</span>()<span class="op">;</span> <span class="co">// Update the tier whenever points are changed</span></span>
<span id="cb3-25"><a href="#cb3-25" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb3-26"><a href="#cb3-26" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Points cannot be negative."</span>)<span class="op">;</span></span>
<span id="cb3-27"><a href="#cb3-27" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-28"><a href="#cb3-28" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-29"><a href="#cb3-29" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-30"><a href="#cb3-30" aria-hidden="true" tabindex="-1"></a> <span class="co">// Getter for tier</span></span>
<span id="cb3-31"><a href="#cb3-31" aria-hidden="true" tabindex="-1"></a> <span class="kw">get</span> <span class="fu">tier</span>() {</span>
<span id="cb3-32"><a href="#cb3-32" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">this</span><span class="op">.</span>#<span class="at">tier</span><span class="op">;</span></span>
<span id="cb3-33"><a href="#cb3-33" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-34"><a href="#cb3-34" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-35"><a href="#cb3-35" aria-hidden="true" tabindex="-1"></a> <span class="co">// Getter for VIP status</span></span>
<span id="cb3-36"><a href="#cb3-36" aria-hidden="true" tabindex="-1"></a> <span class="kw">get</span> <span class="fu">isVIP</span>() {</span>
<span id="cb3-37"><a href="#cb3-37" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">this</span><span class="op">.</span>#<span class="at">isVIP</span><span class="op">;</span></span>
<span id="cb3-38"><a href="#cb3-38" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-39"><a href="#cb3-39" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-40"><a href="#cb3-40" aria-hidden="true" tabindex="-1"></a> <span class="co">// Setter for VIP status</span></span>
<span id="cb3-41"><a href="#cb3-41" aria-hidden="true" tabindex="-1"></a> <span class="kw">set</span> <span class="fu">isVIP</span>(status) {</span>
<span id="cb3-42"><a href="#cb3-42" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (<span class="kw">typeof</span> status <span class="op">===</span> <span class="st">'boolean'</span>) {</span>
<span id="cb3-43"><a href="#cb3-43" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">isVIP</span> <span class="op">=</span> status<span class="op">;</span> <span class="co">// Update VIP status only if a boolean is passed</span></span>
<span id="cb3-44"><a href="#cb3-44" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb3-45"><a href="#cb3-45" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Invalid status. Must be true or false."</span>)<span class="op">;</span></span>
<span id="cb3-46"><a href="#cb3-46" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-47"><a href="#cb3-47" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-48"><a href="#cb3-48" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-49"><a href="#cb3-49" aria-hidden="true" tabindex="-1"></a> <span class="co">// Private method to update the tier based on points</span></span>
<span id="cb3-50"><a href="#cb3-50" aria-hidden="true" tabindex="-1"></a> #<span class="fu">updateTier</span>() {</span>
<span id="cb3-51"><a href="#cb3-51" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (<span class="kw">this</span><span class="op">.</span>#<span class="at">points</span> <span class="op">>=</span> <span class="dv">1000</span>) {</span>
<span id="cb3-52"><a href="#cb3-52" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">tier</span> <span class="op">=</span> <span class="st">"Gold"</span><span class="op">;</span></span>
<span id="cb3-53"><a href="#cb3-53" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">isVIP</span> <span class="op">=</span> <span class="kw">true</span><span class="op">;</span> <span class="co">// Automatically grant VIP status for Gold tier</span></span>
<span id="cb3-54"><a href="#cb3-54" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> <span class="cf">if</span> (<span class="kw">this</span><span class="op">.</span>#<span class="at">points</span> <span class="op">>=</span> <span class="dv">500</span>) {</span>
<span id="cb3-55"><a href="#cb3-55" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">tier</span> <span class="op">=</span> <span class="st">"Silver"</span><span class="op">;</span></span>
<span id="cb3-56"><a href="#cb3-56" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">isVIP</span> <span class="op">=</span> <span class="kw">false</span><span class="op">;</span> <span class="co">// No automatic VIP status for Silver tier</span></span>
<span id="cb3-57"><a href="#cb3-57" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb3-58"><a href="#cb3-58" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span>#<span class="at">tier</span> <span class="op">=</span> <span class="st">"Bronze"</span><span class="op">;</span></span>
<span id="cb3-59"><a href="#cb3-59" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">isVIP</span> <span class="op">=</span> <span class="kw">false</span><span class="op">;</span> <span class="co">// No VIP status for Bronze tier</span></span>
<span id="cb3-60"><a href="#cb3-60" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-61"><a href="#cb3-61" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-62"><a href="#cb3-62" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-63"><a href="#cb3-63" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to display the customer details</span></span>
<span id="cb3-64"><a href="#cb3-64" aria-hidden="true" tabindex="-1"></a> <span class="fu">displayDetails</span>() {</span>
<span id="cb3-65"><a href="#cb3-65" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Customer: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb3-66"><a href="#cb3-66" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Points: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">points</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb3-67"><a href="#cb3-67" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Tier: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">tier</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb3-68"><a href="#cb3-68" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`VIP Status: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">isVIP</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb3-69"><a href="#cb3-69" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb3-70"><a href="#cb3-70" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb3-71"><a href="#cb3-71" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-72"><a href="#cb3-72" aria-hidden="true" tabindex="-1"></a><span class="co">// Example usage:</span></span>
<span id="cb3-73"><a href="#cb3-73" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-74"><a href="#cb3-74" aria-hidden="true" tabindex="-1"></a><span class="co">// Create a new loyalty program instance for a customer</span></span>
<span id="cb3-75"><a href="#cb3-75" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> customerLoyalty <span class="op">=</span> <span class="kw">new</span> <span class="fu">LoyaltyProgram</span>(<span class="st">"Bob Johnson"</span>)<span class="op">;</span></span>
<span id="cb3-76"><a href="#cb3-76" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-77"><a href="#cb3-77" aria-hidden="true" tabindex="-1"></a><span class="co">// Add points using the setter</span></span>
<span id="cb3-78"><a href="#cb3-78" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="at">points</span> <span class="op">=</span> <span class="dv">600</span><span class="op">;</span> <span class="co">// Points are updated and tier is automatically recalculated</span></span>
<span id="cb3-79"><a href="#cb3-79" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-80"><a href="#cb3-80" aria-hidden="true" tabindex="-1"></a><span class="co">// Check the customer's details</span></span>
<span id="cb3-81"><a href="#cb3-81" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="fu">displayDetails</span>()<span class="op">;</span> <span class="co">// Outputs:</span></span>
<span id="cb3-82"><a href="#cb3-82" aria-hidden="true" tabindex="-1"></a><span class="co">// Customer: Bob Johnson</span></span>
<span id="cb3-83"><a href="#cb3-83" aria-hidden="true" tabindex="-1"></a><span class="co">// Points: 600</span></span>
<span id="cb3-84"><a href="#cb3-84" aria-hidden="true" tabindex="-1"></a><span class="co">// Tier: Silver</span></span>
<span id="cb3-85"><a href="#cb3-85" aria-hidden="true" tabindex="-1"></a><span class="co">// VIP Status: false</span></span>
<span id="cb3-86"><a href="#cb3-86" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-87"><a href="#cb3-87" aria-hidden="true" tabindex="-1"></a><span class="co">// Add more points</span></span>
<span id="cb3-88"><a href="#cb3-88" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="at">points</span> <span class="op">=</span> <span class="dv">1200</span><span class="op">;</span> <span class="co">// Points are updated, tier changes to Gold, and VIP status is granted</span></span>
<span id="cb3-89"><a href="#cb3-89" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-90"><a href="#cb3-90" aria-hidden="true" tabindex="-1"></a><span class="co">// Check the updated details</span></span>
<span id="cb3-91"><a href="#cb3-91" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="fu">displayDetails</span>()<span class="op">;</span> <span class="co">// Outputs:</span></span>
<span id="cb3-92"><a href="#cb3-92" aria-hidden="true" tabindex="-1"></a><span class="co">// Customer: Bob Johnson</span></span>
<span id="cb3-93"><a href="#cb3-93" aria-hidden="true" tabindex="-1"></a><span class="co">// Points: 1200</span></span>
<span id="cb3-94"><a href="#cb3-94" aria-hidden="true" tabindex="-1"></a><span class="co">// Tier: Gold</span></span>
<span id="cb3-95"><a href="#cb3-95" aria-hidden="true" tabindex="-1"></a><span class="co">// VIP Status: true</span></span>
<span id="cb3-96"><a href="#cb3-96" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-97"><a href="#cb3-97" aria-hidden="true" tabindex="-1"></a><span class="co">// Attempt to set negative points (invalid)</span></span>
<span id="cb3-98"><a href="#cb3-98" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="at">points</span> <span class="op">=</span> <span class="op">-</span><span class="dv">100</span><span class="op">;</span> <span class="co">// Outputs: "Points cannot be negative."</span></span>
<span id="cb3-99"><a href="#cb3-99" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-100"><a href="#cb3-100" aria-hidden="true" tabindex="-1"></a><span class="co">// Manually update VIP status (even though it's typically set by the tier)</span></span>
<span id="cb3-101"><a href="#cb3-101" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="at">isVIP</span> <span class="op">=</span> <span class="kw">false</span><span class="op">;</span> <span class="co">// VIP status is manually overridden</span></span>
<span id="cb3-102"><a href="#cb3-102" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-103"><a href="#cb3-103" aria-hidden="true" tabindex="-1"></a><span class="co">// Display the details again</span></span>
<span id="cb3-104"><a href="#cb3-104" aria-hidden="true" tabindex="-1"></a>customerLoyalty<span class="op">.</span><span class="fu">displayDetails</span>()<span class="op">;</span> <span class="co">// Outputs:</span></span>
<span id="cb3-105"><a href="#cb3-105" aria-hidden="true" tabindex="-1"></a><span class="co">// Customer: Bob Johnson</span></span>
<span id="cb3-106"><a href="#cb3-106" aria-hidden="true" tabindex="-1"></a><span class="co">// Points: 1200</span></span>
<span id="cb3-107"><a href="#cb3-107" aria-hidden="true" tabindex="-1"></a><span class="co">// Tier: Gold</span></span>
<span id="cb3-108"><a href="#cb3-108" aria-hidden="true" tabindex="-1"></a><span class="co">// VIP Status: false</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</section>
<section id="explanation-1" class="level3">
<h3 class="anchored" data-anchor-id="explanation-1">Explanation:</h3>
<ul>
<li><strong>Private properties</strong>: The properties <code>#points</code>, <code>#tier</code>, and <code>#isVIP</code> are private and can only be accessed or modified within the class itself. This ensures encapsulation.</li>
<li><strong>Getters and Setters</strong>: Getters are used to retrieve private property values, while setters allow us to validate and update the values. The setter for <code>points</code> triggers the private method <code>#updateTier()</code> to adjust the tier and VIP status automatically based on the customer’s points.</li>
<li><strong>Private methods</strong>: The <code>#updateTier()</code> method is private and not accessible from outside the class. It automatically updates the customer’s tier and VIP status based on their points.</li>
</ul>
<p>This pattern helps maintain control over how the properties are accessed and modified, ensuring that the program’s logic stays consistent and reliable.</p>
<p>Here’s an example using static methods in a business case for a bank that processes account transactions. Static methods are used to handle shared functionality that doesn’t rely on an individual instance of the class, like calculating transaction fees based on a provided amount.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode javascript code-with-copy"><code class="sourceCode javascript"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="co">// Class representing a Bank Account</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> BankAccount {</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">constructor</span>(accountNumber<span class="op">,</span> customerName<span class="op">,</span> balance <span class="op">=</span> <span class="dv">0</span>) {</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">accountNumber</span> <span class="op">=</span> accountNumber<span class="op">;</span> <span class="co">// Unique account number</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">customerName</span> <span class="op">=</span> customerName<span class="op">;</span> <span class="co">// The name of the account holder</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">balance</span> <span class="op">=</span> balance<span class="op">;</span> <span class="co">// Account balance, default is 0</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to deposit money into the account</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a> <span class="fu">deposit</span>(amount) {</span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (amount <span class="op">></span> <span class="dv">0</span>) {</span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">balance</span> <span class="op">+=</span> amount<span class="op">;</span> <span class="co">// Add the deposit amount to the balance</span></span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Deposited $</span><span class="sc">${</span>amount<span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="sc">}</span><span class="vs"> into account.`</span>)<span class="op">;</span></span>
<span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Deposit amount must be greater than 0."</span>)<span class="op">;</span></span>
<span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-17"><a href="#cb4-17" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-18"><a href="#cb4-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-19"><a href="#cb4-19" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to withdraw money from the account</span></span>
<span id="cb4-20"><a href="#cb4-20" aria-hidden="true" tabindex="-1"></a> <span class="fu">withdraw</span>(amount) {</span>
<span id="cb4-21"><a href="#cb4-21" aria-hidden="true" tabindex="-1"></a> <span class="kw">const</span> fee <span class="op">=</span> BankAccount<span class="op">.</span><span class="fu">calculateTransactionFee</span>(amount)<span class="op">;</span> <span class="co">// Static method to calculate transaction fees</span></span>
<span id="cb4-22"><a href="#cb4-22" aria-hidden="true" tabindex="-1"></a> <span class="kw">const</span> totalAmount <span class="op">=</span> amount <span class="op">+</span> fee<span class="op">;</span> <span class="co">// Total withdrawal amount includes the fee</span></span>
<span id="cb4-23"><a href="#cb4-23" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (amount <span class="op">></span> <span class="dv">0</span> <span class="op">&&</span> totalAmount <span class="op"><=</span> <span class="kw">this</span><span class="op">.</span><span class="at">balance</span>) {</span>
<span id="cb4-24"><a href="#cb4-24" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="at">balance</span> <span class="op">-=</span> totalAmount<span class="op">;</span> <span class="co">// Deduct the total withdrawal amount from the balance</span></span>
<span id="cb4-25"><a href="#cb4-25" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Withdrew $</span><span class="sc">${</span>amount<span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="sc">}</span><span class="vs">, including a fee of $</span><span class="sc">${</span>fee<span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="sc">}</span><span class="vs">.`</span>)<span class="op">;</span></span>
<span id="cb4-26"><a href="#cb4-26" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb4-27"><a href="#cb4-27" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="st">"Insufficient balance or invalid withdrawal amount."</span>)<span class="op">;</span></span>
<span id="cb4-28"><a href="#cb4-28" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-29"><a href="#cb4-29" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-30"><a href="#cb4-30" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-31"><a href="#cb4-31" aria-hidden="true" tabindex="-1"></a> <span class="co">// Static method to calculate transaction fees based on the amount</span></span>
<span id="cb4-32"><a href="#cb4-32" aria-hidden="true" tabindex="-1"></a> <span class="kw">static</span> <span class="fu">calculateTransactionFee</span>(amount) {</span>
<span id="cb4-33"><a href="#cb4-33" aria-hidden="true" tabindex="-1"></a> <span class="kw">const</span> feeRate <span class="op">=</span> <span class="fl">0.02</span><span class="op">;</span> <span class="co">// 2% transaction fee</span></span>
<span id="cb4-34"><a href="#cb4-34" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> amount <span class="op">*</span> feeRate<span class="op">;</span> <span class="co">// Calculate fee based on the amount</span></span>
<span id="cb4-35"><a href="#cb4-35" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-36"><a href="#cb4-36" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-37"><a href="#cb4-37" aria-hidden="true" tabindex="-1"></a> <span class="co">// Static method to compare two accounts based on balance</span></span>
<span id="cb4-38"><a href="#cb4-38" aria-hidden="true" tabindex="-1"></a> <span class="kw">static</span> <span class="fu">compareAccounts</span>(account1<span class="op">,</span> account2) {</span>
<span id="cb4-39"><a href="#cb4-39" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> (account1<span class="op">.</span><span class="at">balance</span> <span class="op">></span> account2<span class="op">.</span><span class="at">balance</span>) {</span>
<span id="cb4-40"><a href="#cb4-40" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="vs">`</span><span class="sc">${</span>account1<span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs"> has a higher balance than </span><span class="sc">${</span>account2<span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs">.`</span><span class="op">;</span></span>
<span id="cb4-41"><a href="#cb4-41" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> <span class="cf">if</span> (account1<span class="op">.</span><span class="at">balance</span> <span class="op"><</span> account2<span class="op">.</span><span class="at">balance</span>) {</span>
<span id="cb4-42"><a href="#cb4-42" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="vs">`</span><span class="sc">${</span>account2<span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs"> has a higher balance than </span><span class="sc">${</span>account1<span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs">.`</span><span class="op">;</span></span>
<span id="cb4-43"><a href="#cb4-43" aria-hidden="true" tabindex="-1"></a> } <span class="cf">else</span> {</span>
<span id="cb4-44"><a href="#cb4-44" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="vs">`Both accounts have the same balance.`</span><span class="op">;</span></span>
<span id="cb4-45"><a href="#cb4-45" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-46"><a href="#cb4-46" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-47"><a href="#cb4-47" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-48"><a href="#cb4-48" aria-hidden="true" tabindex="-1"></a> <span class="co">// Method to display the account details</span></span>
<span id="cb4-49"><a href="#cb4-49" aria-hidden="true" tabindex="-1"></a> <span class="fu">displayDetails</span>() {</span>
<span id="cb4-50"><a href="#cb4-50" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Account Number: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">accountNumber</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb4-51"><a href="#cb4-51" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Customer Name: </span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">customerName</span><span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb4-52"><a href="#cb4-52" aria-hidden="true" tabindex="-1"></a> <span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Balance: $</span><span class="sc">${</span><span class="kw">this</span><span class="op">.</span><span class="at">balance</span><span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="sc">}</span><span class="vs">`</span>)<span class="op">;</span></span>
<span id="cb4-53"><a href="#cb4-53" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb4-54"><a href="#cb4-54" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb4-55"><a href="#cb4-55" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-56"><a href="#cb4-56" aria-hidden="true" tabindex="-1"></a><span class="co">// Example usage:</span></span>
<span id="cb4-57"><a href="#cb4-57" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-58"><a href="#cb4-58" aria-hidden="true" tabindex="-1"></a><span class="co">// Create two accounts</span></span>
<span id="cb4-59"><a href="#cb4-59" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> account1 <span class="op">=</span> <span class="kw">new</span> <span class="fu">BankAccount</span>(<span class="dv">123456</span><span class="op">,</span> <span class="st">"Alice Johnson"</span><span class="op">,</span> <span class="dv">1000</span>)<span class="op">;</span></span>
<span id="cb4-60"><a href="#cb4-60" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> account2 <span class="op">=</span> <span class="kw">new</span> <span class="fu">BankAccount</span>(<span class="dv">654321</span><span class="op">,</span> <span class="st">"Bob Williams"</span><span class="op">,</span> <span class="dv">1500</span>)<span class="op">;</span></span>
<span id="cb4-61"><a href="#cb4-61" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-62"><a href="#cb4-62" aria-hidden="true" tabindex="-1"></a><span class="co">// Deposit money into account1</span></span>
<span id="cb4-63"><a href="#cb4-63" aria-hidden="true" tabindex="-1"></a>account1<span class="op">.</span><span class="fu">deposit</span>(<span class="dv">500</span>)<span class="op">;</span> <span class="co">// Deposits $500 into Alice's account</span></span>
<span id="cb4-64"><a href="#cb4-64" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-65"><a href="#cb4-65" aria-hidden="true" tabindex="-1"></a><span class="co">// Withdraw money from account1</span></span>
<span id="cb4-66"><a href="#cb4-66" aria-hidden="true" tabindex="-1"></a>account1<span class="op">.</span><span class="fu">withdraw</span>(<span class="dv">300</span>)<span class="op">;</span> <span class="co">// Withdraws $300 from Alice's account, including a 2% fee</span></span>
<span id="cb4-67"><a href="#cb4-67" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-68"><a href="#cb4-68" aria-hidden="true" tabindex="-1"></a><span class="co">// Display account details</span></span>
<span id="cb4-69"><a href="#cb4-69" aria-hidden="true" tabindex="-1"></a>account1<span class="op">.</span><span class="fu">displayDetails</span>()<span class="op">;</span> <span class="co">// Displays Alice's updated account details</span></span>
<span id="cb4-70"><a href="#cb4-70" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-71"><a href="#cb4-71" aria-hidden="true" tabindex="-1"></a><span class="co">// Compare balances of two accounts using the static method</span></span>
<span id="cb4-72"><a href="#cb4-72" aria-hidden="true" tabindex="-1"></a><span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(BankAccount<span class="op">.</span><span class="fu">compareAccounts</span>(account1<span class="op">,</span> account2))<span class="op">;</span> <span class="co">// Outputs comparison of balances between Alice and Bob</span></span>
<span id="cb4-73"><a href="#cb4-73" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-74"><a href="#cb4-74" aria-hidden="true" tabindex="-1"></a><span class="co">// Calculate transaction fee directly using the static method</span></span>
<span id="cb4-75"><a href="#cb4-75" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> fee <span class="op">=</span> BankAccount<span class="op">.</span><span class="fu">calculateTransactionFee</span>(<span class="dv">200</span>)<span class="op">;</span> <span class="co">// Calculates the fee for a $200 transaction</span></span>
<span id="cb4-76"><a href="#cb4-76" aria-hidden="true" tabindex="-1"></a><span class="bu">console</span><span class="op">.</span><span class="fu">log</span>(<span class="vs">`Transaction fee for $200 is $</span><span class="sc">${</span>fee<span class="op">.</span><span class="fu">toFixed</span>(<span class="dv">2</span>)<span class="sc">}</span><span class="vs">.`</span>)<span class="op">;</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</section>
<section id="explanation-2" class="level3">
<h3 class="anchored" data-anchor-id="explanation-2">Explanation:</h3>
<ul>
<li><strong>Static Methods</strong>: <code>calculateTransactionFee</code> and <code>compareAccounts</code> are static methods that belong to the class itself rather than any specific instance. They can be called directly on the class (e.g., <code>BankAccount.calculateTransactionFee</code>) and are typically used for utility functions or class-level logic.</li>
<li><strong>Instance Methods</strong>: Methods like <code>deposit</code>, <code>withdraw</code>, and <code>displayDetails</code> rely on individual instances of <code>BankAccount</code> to interact with specific data like <code>accountNumber</code> or <code>balance</code>.</li>
<li><strong>Business Case</strong>: The static <code>calculateTransactionFee</code> method calculates a 2% fee for a withdrawal based on the amount, while the <code>compareAccounts</code> method compares the balances of two different <code>BankAccount</code> instances.</li>
</ul>
<p>Static methods are useful when you want to create shared behavior that isn’t tied to any particular instance of a class but instead provides functionality relevant to the entire class.</p>
</section>
</main>
<!-- /main column -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
// For code content inside modals, clipBoardJS needs to be initialized with a container option
// TODO: Check when it could be a function (https://github.com/zenorocha/clipboard.js/issues/860)
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
// TODO in 1.5, we should make sure this works without a callout special case
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
</div> <!-- /content -->
</body></html>