create a class in javascript

In ECMAScript 2015 or later versions, we can create a class in JavaScript using the class keyword. A class is essentially a syntax for creating objects with predefined properties and methods.

To define a class, we first need to use the class keyword followed by the name of the class. Here's an example:

index.tsx
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
}
163 chars
11 lines

In the above code, we have defined a Person class with a constructor that takes in two parameters name and age. We have also defined a method sayHello which logs a greeting to the console.

To create an instance of a class, we simply use the new keyword followed by the name of the class and any arguments required by the constructor. Here's an example:

index.tsx
const johnDoe = new Person('John Doe', 30);
johnDoe.sayHello(); // logs "Hello, my name is John Doe"
101 chars
3 lines

In the above code, we have created a new instance of the Person class and passed in the arguments 'John Doe' and 30.

We can also add methods to a class using the prototype property. Here's an example:

index.tsx
Person.prototype.sayAge = function() {
  console.log(`I am ${this.age} years old`);
}

johnDoe.sayAge(); // logs "I am 30 years old"
133 chars
6 lines

In the above code, we have added a sayAge method to the Person class using the prototype property. We can then call this method on any instance of the Person class, such as johnDoe.

gistlibby LogSnag