In JavaScript, you can define a
class using the `class` keyword. Here's the basic syntax to define a class in JavaScript:
class ClassName {
// Class properties
// Constructor
constructor() {
// Initialize properties
}
// Methods
methodName() {
// Method logic
}
}
Let's break down the syntax:
- `class ClassName` declares a new class with the name "ClassName". You can replace "ClassName" with the desired name for your class.
- The class body is wrapped in curly braces `{}` and contains the properties and methods of the class.
- The `constructor` method is a special method that is executed when an instance of the class is created. It is used to initialize the class properties. You can define the constructor using the `constructor` keyword followed by parentheses `()`.
- Inside the class body, you can define other methods that perform specific actions or computations. Methods are defined without the `function` keyword.
Here's an example of defining a simple class in JavaScript:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
// Creating an instance of the Person class
const john = new Person('John', 30);
// Accessing properties and calling methods
console.log(john.name); // Output: John
console.log(john.age); // Output: 30
john.greet(); // Output: Hello, my name is John and I'm 30 years old.
In this example, the `Person` class has two properties (`name` and `age`) and a method (`greet`). The `constructor` initializes the `name` and `age` properties, and the `greet` method logs a greeting message to the console.
You can create instances of the
class using the `new` keyword, as shown in the example with the `john`
object. Then you can access the properties and call the methods on the instance.