create class in javascript

In JavaScript, you can create a class using the class keyword, which allows you to define the properties and methods of the class.

Here's an example of a class that represents a person:

index.tsx
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}
194 chars
11 lines

In the above example, the Person class has a constructor method that takes in a name and age parameter and sets them as properties of the class instance. It also has a sayHello method that logs a greeting including the name and age of the person.

To create an instance of the Person class, you can use the new keyword:

index.tsx
const john = new Person('John', 30);
john.sayHello(); // Output: "Hello, my name is John and I'm 30 years old."
112 chars
3 lines

gistlibby LogSnag