This project demonstrates how a JavaScript class works using a simple Person example. The Person class is a blueprint used to create person objects, each containing a first name and a last name. The constructor initializes these values when a new object is created. A method called getFullName() combines and returns the first and last names. In the HTML, a button is provided that triggers the showPerson() function when clicked. This function creates a new Person object, calls its method to get the full name, and then displays the result dynamically on the webpage. This shows how JavaScript classes, objects, methods, and DOM manipulation work together in a basic project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Person Class Example</title>
</head>
<body>
<!-- Heading shown on the webpage -->
<h1>JavaScript Person Class Example</h1>
<!-- Button to trigger JavaScript function -->
<button onclick="showPerson()">Show Person Details</button>
<!-- Paragraph where output will be displayed -->
<p id="output"></p>
<script>
// Define a class named Person
class Person {
// Constructor method runs when a new object is created
constructor(firstname, lastname) {
// Assign the firstname parameter to the object's firstname property
this.firstname = firstname;
// Assign the lastname parameter to the object's lastname property
this.lastname = lastname;
}
// Method to return the full name of the person
getFullName() {
// Combine firstname and lastname and return them
return this.firstname + " " + this.lastname;
}
}
// Function that runs when the button is clicked
function showPerson() {
// Create a new Person object with first and last name
const person1 = new Person("John", "Doe");
// Get the paragraph element by its ID
const outputElement = document.getElementById("output");
// Display the full name inside the paragraph
outputElement.textContent = "Full Name: " + person1.getFullName();
}
</script>
</body>
</html>