Class basic syntax in JavaScript

In JavaScript, classes are a way of defining reusable blueprints for objects. The basic syntax for creating a class in JavaScript is as follows:

javascript
class ClassName {
  // class methods and properties
  constructor() {
    // constructor code
  }
  
  method1() {
    // method1 code
  }
  
  method2() {
    // method2 code
  }
  
  // ...
}

In this syntax:

  • class keyword is used to define a class.
  • ClassName is the name of the class. This should be in UpperCamelCase.
  • constructor() is a special method that is called when an object of the class is created. This is where you can define the initial state of the object and set up any properties or methods.
  • method1() and method2() are additional methods that can be defined on the class. These can be used to perform operations on objects of the class.

Here's an example of how you can create an object of the class and call its methods:

javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHello() {
    console.log(`Hello, my name is ${this.name}.`);
  }
  
  sayAge() {
    console.log(`I am ${this.age} years old.`);
  }
}

const john = new Person("John", 30);
john.sayHello(); // Output: Hello, my name is John.
john.sayAge(); // Output: I am 30 years old.

In this example, we define a Person class with a constructor that sets the name and age properties. We also define two methods sayHello() and sayAge() that log some information about the person. We then create a new Person object named john with the new keyword and call its methods.

0 Comments

You can use the contact form below to send us a message

We would love to hear from you! If you have any questions, comments, or suggestions, please feel free to get in touch with us.