자바스크립트 클래스 생성자 (Class Constructors)

In JavaScript, Class Constructors are used to create objects based on a blueprint called a class. A class is a template for creating objects that share the same properties and methods.

Creating a Class Constructor

To create a class constructor in JavaScript, we use the class keyword followed by the name of the class. Inside the class, we define properties and methods.

Here’s an example of a class constructor that represents a Person:

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

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

In the code above, we define a class named Person with two properties: name and age. The constructor method is a special method used to initialize the object’s properties when a new instance of the class is created.

Creating Instances of a Class

Once we have a class constructor, we can create instances of that class using the new keyword.

const john = new Person("John", 25);
const jane = new Person("Jane", 30);

john.greet(); // Output: Hello, my name is John and I am 25 years old.
jane.greet(); // Output: Hello, my name is Jane and I am 30 years old.

In the code above, we create two instances of the Person class: john and jane. We pass the values "John" and 25 as arguments to the Person constructor for the john instance, and "Jane" and 30 for the jane instance.

Class Inheritance

One of the benefits of using class constructors is that we can easily create new classes based on existing ones through class inheritance.

To create a subclass, we use the extends keyword, followed by the name of the class we want to inherit from.

class Student extends Person {
  constructor(name, age, major) {
    super(name, age);
    this.major = major;
  }

  study() {
    console.log(`I am studying ${this.major}.`);
  }
}

In the code above, we define a subclass Student that extends the Person class. The super keyword is used to call the constructor of the parent class.

Now, we can create instances of the Student class and access both the properties and methods inherited from the Person class, as well as the new properties and methods defined in the Student class.

const amy = new Student("Amy", 20, "Computer Science");

amy.greet(); // Output: Hello, my name is Amy and I am 20 years old.
amy.study(); // Output: I am studying Computer Science.

In the code above, we create an instance of the Student class named amy. We can call the greet method inherited from the Person class, as well as the study method defined in the Student class.

Conclusion

Class constructors in JavaScript provide a way to define and create objects based on a blueprint. They allow us to organize our code in a more structured and reusable manner. Class inheritance further enhances the flexibility of creating new classes based on existing ones.