create a new class in javascript

In JavaScript, since the release of ECMAScript 6, the class syntax was introduced which makes it much easier to create classes in JavaScript. Here is an example of how to create a new class:

index.tsx
class Person {
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }

  greeting() {
    return `Hi, my name is ${this.name} and I am ${this.age} years old.`;
  }

  sayGender() {
    return `I am ${this.gender}.`;
  }
}
274 chars
16 lines

In the above example, Person is the name of the new class we are creating. We are using the class keyword to define the class. The constructor method is called when an object is created based on this class, and it is used to initialize the object's properties. The greeting() and sayGender() methods are added to the class, which enable objects created based on this class to perform certain actions or retrieve information.

To create a new instance of the Person class, we can simply do the following:

index.tsx
let person1 = new Person("John", 30, "male");
46 chars
2 lines

In the above example, person1 is a new object based on the Person class. We are passing in the values "John", 30, and "male" to the constructor method to set the name, age, and gender properties of the person1 object. Finally, we can call the greeting() and sayGender() methods on the person1 object to retrieve the desired information.

index.tsx
console.log(person1.greeting()); // Output: "Hi, my name is John and I am 30 years old."
console.log(person1.sayGender()); // Output: "I am male."
147 chars
3 lines

gistlibby LogSnag