π JavaScript OOP Classes and Object Instances
In Object-Oriented Programming (OOP), classes and objects are fundamental building blocks. Understanding how they work is crucial to mastering OOP concepts.
Classes
A class is like a blueprint for creating objects. It defines a template that specifies the properties (data) and methods (functions) that the objects created from the class will have. Think of a class as a set of instructions that tell the computer how to create an object.
For example, letβs consider a Student
class. This class might include properties like name
and studentID
, and methods like enroll()
. Every student created from this class will have these properties and methods.
class Student {
constructor(name, studentID) {
this.name = name;
this.studentID = studentID;
}
enroll(course) {
console.log(`${this.name} has enrolled in ${course}.`);
}
}
Object Instances
An object is an instance of a class. When you create an object, you are creating a concrete example of the class, with actual data stored in its properties. Each object has its own set of properties, based on the class from which it was created.
For instance, using the Student
class, we can create a specific student object:
const student1 = new Student("John Doe", "S12345");
console.log(student1.name); // Outputs: John Doe
student1.enroll("Math 101"); // Outputs: John Doe has enrolled in Math 101.
In this example, student1
is an object (or instance) of the Student
class. It has its own name
and studentID
properties, and it can use the methods defined in the Student
class, such as enroll()
.
Creating Multiple Objects
One of the key advantages of using classes is that you can create multiple objects from the same class, each with its own unique data. This is useful when you need to manage several similar items in your program.
const student1 = new Student("John Doe", "S12345");
const student2 = new Student("Jane Smith", "S67890");
console.log(student1.name); // Outputs: John Doe
console.log(student2.name); // Outputs: Jane Smith
student1.enroll("Math 101"); // Outputs: John Doe has enrolled in Math 101.
student2.enroll("History 201"); // Outputs: Jane Smith has enrolled in History 201.
In this example, student1
and student2
are both instances of the Student
class, but they have different data (names and IDs). Each object operates independently, meaning enrolling student1
in a course doesnβt affect student2
.
Summary
- Class
- A blueprint that defines the structure and behavior of objects.
- Object
- An instance of a class, with its own unique data and the ability to use the methods defined in the class.
- Multiple Objects
- You can create as many objects as you need from the same class, each with its own unique properties.
Putting It Into Action
To see how classes and objects work in practice, let's create a simple Student Management System. In this example, we'll use the Student
class to manage student records, including enrolling students in courses.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Management System</title>
</head>
<body>
<h1>Student Management System</h1>
<h2>Add a New Student</h2>
<form id="addStudentForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="studentID">Student ID:</label>
<input type="text" id="studentID" name="studentID"><br><br>
<button type="submit">Add Student</button>
</form>
<h2>Student Records</h2>
<ul id="studentList"></ul>
<script>
class Student {
constructor(name, studentID) {
this.name = name;
this.studentID = studentID;
}
enroll(course) {
return `${this.name} has enrolled in ${course}.`;
}
getDetails() {
return `${this.name} (ID: ${this.studentID})`;
}
}
class School {
constructor() {
this.students = [];
}
addStudent(student) {
this.students.push(student);
}
listStudents() {
return this.students;
}
}
const school = new School();
document.getElementById('addStudentForm').addEventListener('submit', function(event) {
event.preventDefault();
const name = document.getElementById('name').value;
const studentID = document.getElementById('studentID').value;
const newStudent = new Student(name, studentID);
school.addStudent(newStudent);
updateStudentList();
});
function updateStudentList() {
const studentList = document.getElementById('studentList');
studentList.innerHTML = '';
school.listStudents().forEach((student, index) => {
const li = document.createElement('li');
li.textContent = student.getDetails();
const courseButton = document.createElement('button');
courseButton.textContent = 'Enroll in Course';
courseButton.addEventListener('click', () => {
const course = prompt(`Enter course to enroll for ${student.name}:`);
if (course) {
alert(student.enroll(course));
}
});
li.appendChild(courseButton);
studentList.appendChild(li);
});
}
</script>
</body>
</html>
Challenge
Now that you've built a basic Student Management System, let's add more functionality. Here's your challenge:
- Add functionality to update a student's grade. Create a new method in the
Student
class calledupdateGrade()
. - Modify the "Putting It Into Action" example to include a button for updating the grade for each student. When clicked, the button should prompt the user to enter a new grade and then update the student's grade accordingly.
In order to check your learning, you should attempt to create a solution before revealing the provided solution below.
// JavaScript Code for the Challenge Solution
class Student {
constructor(name, studentID, grade) {
this.name = name;
this.studentID = studentID;
this.grade = grade || 'N/A'; // Default grade if not provided
}
enroll(course) {
return `${this.name} has enrolled in ${course}.`;
}
updateGrade(newGrade) {
this.grade = newGrade;
return `${this.name}'s grade has been updated to ${this.grade}.`;
}
getDetails() {
return `${this.name} (ID: ${this.studentID}) - Grade: ${this.grade}`;
}
}
// School class remains unchanged
// Modify the updateStudentList function to include a grade update button
function updateStudentList() {
const studentList = document.getElementById('studentList');
studentList.innerHTML = '';
school.listStudents().forEach((student, index) => {
const li = document.createElement('li');
li.textContent = student.getDetails();
const courseButton = document.createElement('button');
courseButton.textContent = 'Enroll in Course';
courseButton.addEventListener('click', () => {
const course = prompt(`Enter course to enroll for ${student.name}:`);
if (course) {
alert(student.enroll(course));
}
});
const gradeButton = document.createElement('button');
gradeButton.textContent = 'Update Grade';
gradeButton.addEventListener('click', () => {
const newGrade = prompt(`Enter new grade for ${student.name}:`, student.grade);
if (newGrade) {
alert(student.updateGrade(newGrade));
updateStudentList(); // Refresh the list to show the updated grade
}
});
li.appendChild(courseButton);
li.appendChild(gradeButton);
studentList.appendChild(li);
});
}