자바스크립트 클래스 속성 (Class Properties)

Before class properties were introduced, developers had to manually define and assign values to properties inside the constructor or in separate methods. With the advent of class properties, though, the process has become much simpler and more concise.

To define a class property in JavaScript, we can make use of the new class field declaration syntax. This syntax allows us to directly assign a value to a property within the class body, without the need for any specific methods.

Let’s consider an example of a Person class with a name property:

class Person {
  name = "John Doe";

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const person = new Person();
person.greet(); // Output: Hello, my name is John Doe

In the above code snippet, the name property is directly initialized with the value “John Doe” using the class field declaration syntax. This means that every instance of the Person class will have a name property with the assigned value.

Class properties can also be modified and accessed just like any other property of an object:

person.name = "Alice Smith";
person.greet(); // Output: Hello, my name is Alice Smith

In addition to initializing class properties directly, we can also use class properties to define static values. Static class properties are shared among all instances of the class and can be accessed without creating an instance:

class Circle {
  static PI = 3.14159;
  radius;

  constructor(radius) {
    this.radius = radius;
  }

  getArea() {
    return Circle.PI * this.radius * this.radius;
  }
}

console.log(Circle.PI); // Output: 3.14159

const circle = new Circle(5);
console.log(circle.getArea()); // Output: 78.53975

In the above example, the PI property is defined as a static class property and is accessible directly on the Circle class itself.

Class properties in JavaScript provide a cleaner and more concise way to define and manage data associated with a class. They make the code more readable and reduce the need for boilerplate constructor or method definitions. If you are using modern versions of JavaScript, considering using class properties to improve the organization and efficiency of your code.