JavaScript Classes
Classes in JavaScript provide a syntax for creating objects using a blueprint-like structure similar to traditional OOP languages. They are syntactic sugar over prototypes, making object creation and inheritance more intuitive.
Key Topics
- Class Declaration
- Constructor and Methods
- Inheritance with extends
- JavaScript Usage in DOM
- Key Takeaways
Class Declaration
Use the class
keyword to define a class. The constructor method initializes new objects.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log("Hello, " + this.name);
}
}
let p = new Person("Alice");
p.greet(); // "Hello, Alice"
Constructor and Methods
The constructor
method runs when you create a new instance. Class methods are defined without the function
keyword inside the class.
Inheritance with extends
Use extends
to create subclasses that inherit from a parent class. Use super()
to call the parent constructor.
JavaScript Usage in DOM
Use classes to structure complex UI components and logic into reusable objects, managing state and behavior more elegantly.
<!DOCTYPE html>
<html>
<head><title>Classes in DOM</title></head>
<body>
<h1>Class Demo</h1>
<button onclick="runDemo()">Run</button>
<p id="message"></p>
<script>
class Greeter {
constructor(elementId) {
this.element = document.getElementById(elementId);
}
greet(name) {
this.element.textContent = "Hello, " + name;
}
}
function runDemo() {
let g = new Greeter("message");
g.greet("Bob");
}
</script>
</body>
</html>
Key Takeaways
- Syntax: Use
class
,constructor
, and methods for OOP-like structure. - Inheritance: Use
extends
andsuper()
for subclassing. - DOM Integration: Organize UI logic in classes for cleaner code.