JavaScript Class Introduction
JavaScript classes, introduced in ES6, provide a cleaner and more structured syntax for creating objects and working with prototypes. They simplify inheritance, method definitions, and object creation.
Key Topics
Defining Classes
A class is defined using the class
keyword, followed by the class name and a set of curly braces.
class Person {
constructor(name) {
this.name = name;
}
}
const person1 = new Person("Alice");
console.log(person1.name);
Output
> Alice
Explanation: The Person
class is instantiated with the new
keyword, creating an object with the name
property.
Constructors
The constructor
method is a special method used to initialize object properties during class instantiation.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
const car1 = new Car("Toyota", "Corolla");
console.log(car1.make, car1.model);
Output
> Toyota Corolla
Explanation: The constructor
initializes the make
and model
properties when a new Car
object is created.
Class Methods
Methods can be defined directly within a class and are automatically added to the prototype of the class.
class Calculator {
add(a, b) {
return a + b;
}
}
const calc = new Calculator();
console.log(calc.add(5, 3));
Output
> 8
Explanation: The add
method is invoked on the calc
object, which belongs to the Calculator
class.
JavaScript Usage in DOM
Below is a complete DOM example using classes to dynamically update webpage content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Class Usage in DOM</title>
</head>
<body>
<button onclick="displayGreeting()">Greet</button>
<p id="output"></p>
<script>
class Greeter {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
function displayGreeting() {
const greeter = new Greeter("Alice");
document.getElementById("output").textContent = greeter.greet();
}
</script>
</body>
</html>
Key Takeaways
- Class Keyword: Defines a blueprint for creating objects.
- Constructors: Special methods for initializing object properties.
- Methods: Functions defined inside a class for reusable operations.
- DOM Integration: Use classes to create dynamic and interactive web applications.