JavaScript(JS) Classes
JavaScript Classes are a way to define objects with properties and methods. They provide a simpler and more organized way to create complex objects and inheritance hierarchies.
Here is an example of a simple JavaScript class:
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } }
In this example, we define a class Person
with a constructor method that takes two arguments name
and age
, and initializes properties with the same names. We also define a method greet
that logs a greeting message to the console.
To create an instance of this class, we can use the new
keyword:
const john = new Person("John", 30); john.greet(); // output: "Hello, my name is John and I am 30 years old."
In this example, we create an instance of the Person
class called john
with the name "John" and age 30. We then call the greet
method on this instance, which logs a greeting message to the console.
JavaScript classes also support inheritance, which allows us to create a hierarchy of related classes with shared properties and methods. Here is an example of a class that extends another class:
class Student extends Person { constructor(name, age, grade) { super(name, age); this.grade = grade; } study() { console.log(`${this.name} is studying for a test.`); } }
In this example, we define a class Student
that extends the Person
class. It has a constructor method that takes three arguments name
, age
, and grade
, and initializes properties with the same names. It also defines a method study
that logs a message to the console.
To create an instance of this class, we can use the new
keyword:
const mary = new Student("Mary", 20, "A"); mary.greet(); // output: "Hello, my name is Mary and I am 20 years old." mary.study(); // output: "Mary is studying for a test."
In this example, we create an instance of the Student
class called mary
with the name "Mary", age 20, and grade "A". We then call the greet
method on this instance, which logs a greeting message to the console. Finally, we call the study
method on this instance, which logs a message to the console.