JavaScript의 생성자 메서드는 클래스 내에서 생성된 객체를 생성하고 초기화하는 데 사용됩니다. 생성자 메서드가 추가되지 않은 경우 기본 생성자를 사용해야 합니다.
참고 − 생성자 메서드는 한 클래스에서 한 번만 사용할 수 있습니다. 둘 이상이 오류를 발생시킵니다.
예시
다음 코드를 실행하여 생성자 메서드를 구현하는 방법을 배울 수 있습니다.
라이브 데모
<html>
<body>
<script>
class Department {
constructor() {
this.name = "Department";
}
}
class Employee extends Department {
constructor() {
super();
}
}
class Company {}
Object.setPrototypeOf(Employee.prototype, Company.prototype);
document.write("<br>"+Object.getPrototypeOf(Employee.prototype) === Department.prototype);
let myInstance = new Employee();
document.write("<br>"+myInstance.name);
</script>
</body>
</html>