Uploaded by Shaqib

JavaScript Classes and Objects Lab Report

advertisement
JavaScript Lab Report: Classes and
Objects
1. Defining a Basic Class and Creating an Object
A class in JavaScript acts as a blueprint for creating objects. It contains a constructor that
initializes object properties, and methods that define behaviors.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
return `Hi, I'm ${this.name}, and I'm ${this.age} years old.`;
}
}
const person1 = new Person("Alice", 22);
document.write(person1.introduce());
2. Adding Multiple Methods in a Class
A class can define more than one method to encapsulate related behaviors. This promotes
code reuse and logical grouping.
class Circle {
constructor(radius) {
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
circumference() {
return 2 * Math.PI * this.radius;
}
}
const circle = new Circle(5);
document.write("Area: " + circle.area() + "<br>");
document.write("Circumference: " + circle.circumference());
3. Using the `this` Keyword
`this` refers to the object that is calling the method. It's used to access the object's
properties and other methods from within the class.
class Laptop {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
showSpecs() {
return `Laptop: ${this.brand} ${this.model}`;
}
}
const myLaptop = new Laptop("Dell", "XPS 13");
document.write(myLaptop.showSpecs());
Download