생성자() 방법이 특별하다. 속성을 초기화하는 곳입니다. 클래스가 시작될 때 자동으로 호출됩니다. 사실 constructor()가 없다면 메소드, 자바스크립트 보이지 않는 빈 constructor() 를 추가합니다. 방법. 우리는 또한 우리 자신의 방법을 자유롭게 만들 수 있습니다. 우리 고유의 메소드 생성은 원래 구문과 동일한 구문을 따릅니다.
예시
다음 예에서는 기본 메서드인 constructor()를 사용하는 대신 속성은 실제로 "anotherMet()라는 사용자 지정 메서드에서 초기화되었습니다. ". 이 방법을 통해 실제 결과를 아래와 같이 출력합니다.
<html>
<body>
<p id="method"></p>
<script>
class Company {
constructor(branch) {
this.name = branch;
}
anotherMet(x) {
return x + " is the head of " + this.name;
}
}
myComp = new Company("Tesla");
document.getElementById("method").innerHTML = myComp.anotherMet("Elon musk");
</script>
</body>
</html> 출력
Elon musk is the head of Tesla