Classes make it easier to create objects and deal with inheritance, encapsulation, and abstraction.
Basic Structure of a Class
A class in JavaScript is defined using the class keyword, followed by a class name. The body of the class contains the constructor method, which is a special method used for creating and initializing objects, and other methods.
helloWorld.js
class Employee {
// Constructor method
constructor(name, age) {
this.name = name; // Assigns the name property
this.age = age; // Assigns the age property
}
// Method
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
// Creating an instance of the class
const emp1 = new Employee('Krishna', 35);
// Accessing methods
emp1.greet();
Output
Hello, my name is Krishna and I am 35 years old.
class Employee { ... }
This line defines a new class called Employee. A class is like a blueprint for creating objects. It contains properties (variables) and methods (functions) that will be shared by all objects created from this class.
constructor(name, age) { ... }
1. The constructor is a special method that gets called automatically whenever a new object is created from this class. It is used to initialize the properties of the object.
2. In this case, the constructor takes two parameters: name and age.
3. this.name = name; and this.age = age;:
a. this refers to the current instance of the class (the object being created).
b. These lines assign the values of name and age to the object's name and age properties.
greet() { ... }
· This is a method (a function that belongs to the class) called greet. Methods define the behaviour of the objects created from the class.
· Inside this method, console.log is used to print a message that includes the object's name and age properties.
Creating an Instance of the Class
const emp1 = new Employee('Krishna', 35);
This line creates a new object (or instance) of the Employee class. The new keyword is used to create a new instance. 'Krishna' and 35 are passed as arguments to the constructor method, so emp1.name will be 'Krishna' and emp1.age will be 35.
Accessing Methods
emp1.greet();
This line calls the greet method on the emp1 object. When greet() is called, it uses the name and age properties of emp1 to display the message "Hello, my name is Krishna and I am 35 years old."
No comments:
Post a Comment