create class with constructor and properties outside constructor in javascript

To create a class with a constructor and properties outside the constructor in JavaScript, you can use the class syntax. Here's an example:

index.tsx
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  set fullName(name) {
    const [firstName, lastName] = name.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.fullName}.`);
  }
}
410 chars
21 lines

In this example, the Person class has a constructor that takes two parameters, firstName and lastName. These parameters are used to set the firstName and lastName properties of the instance being created.

The fullName property is defined using getter and setter methods. The getter returns the full name of the person, while the setter allows you to set the firstName and lastName properties at the same time by providing a full name as a string.

The sayHello method logs a greeting to the console, using the fullName property to get the person's name.

You can create instances of the Person class like this:

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

With this class syntax, you can easily create classes with constructors and properties outside the constructor in JavaScript.

gistlibby LogSnag