JavaScript Classes
JavaScript classes might seem daunting but fear not! Let’s break down the concept using an analogy — think of a class as a cookie cutter. In this discussion, we’ll use a class called Cookie
to illustrate the key concepts.
The Cookie Cutter (Class) Creation:
class Cookie {
constructor(color) {
this.color = color;
}
}
- A class, like a cookie cutter, helps create instances of objects. Always capitalize the class name.
- The
constructor
is like the mold; it shapes new instances of the class. It takes parameters, in this case, a color, and assigns it to the instance.
Baking Cookies (Creating Instances):
let cookieOne = new Cookie('green');
let cookieTwo = new Cookie('blue');
- Using
new
keyword creates specific instances (cookies) based on the class (cookie cutter). - Each instance can have its unique properties.
Decorating Cookies (Getters and Setters):
class Cookie {
constructor(color) {
this.color = color;
}
getColor() {
return this.color;
}
setColor(color) {
this.color = color;
}
}
getColor
andsetColor
are getters and setters, respectively.- They allow us to retrieve and modify the color property of a cookie.
Playing with Cookies (Using Instances):
let cookieOne = new Cookie('green');
let cookieTwo = new Cookie('blue');
console.log(cookieOne.getColor()); // Outputs: 'green'
console.log(cookieTwo.getColor()); // Outputs: 'blue'
cookieOne.setColor('yellow');
console.log(cookieOne.getColor()); // Outputs: 'yellow'
Using methods like getColor
and setColor
allows interaction with instances.
Applying the Concept — Linked List Class:
class LinkedList {
constructor(value) {
// Constructor logic here...
}
push(value) {
// Push logic here...
}
unshift(value) {
// Unshift logic here...
}
insert(index, value) {
// Insert logic here...
}
remove(index) {
// Remove logic here...
}
pop() {
// Pop logic here...
}
shift() {
// Shift logic here...
}
}
let myLinkedList = new LinkedList(23);
myLinkedList.push(7);
myLinkedList.unshift(3);
myLinkedList.insert(1, 11);
myLinkedList.remove(1);
myLinkedList.pop();
myLinkedList.shift();
Using the analogy, a linked list is like a customized set of cookies with specific methods (like push, pop, etc.).
Understanding classes is like having a powerful set of cookie cutters; you can create and customize instances tailored to your needs.
Happy Coding
Bhagya Wijenayake