자바스크립트에서는 자바에서 비슷하게 사용되는 Class 문법을 사용할 수 있으나 내부적으로 돌아가는 방식은 다르다.
class Student{
constructor(name) {
this.group = 14; // 고정 값으로 프로퍼티 초기화
this.name = name; // 인수로 프로퍼티 초기화
}
introduce() {
console.log(`안녕하세요 저는 ${this.group}강의실 학생 ${this.name} 입니다.`);
}
}
let student = new Student('홍길동');
// 생성자 함수와 다르게 new 연산자를 사용하지 않으면 에러 발생
생성자(constructor)는 Class 실행 시 내부적으로 함수로 변환 되어 실행되고 메소드(introduce)부분은 프로토타입 객체로 바뀌어 따로 실행되는 구조이다.
결국, class를 활용해 만들어지는 객체도 함수를 기반으로 만든 객체와 내부원리가 동일하다.
<aside> 📌 Student 예제 내용 정리하면 new Student( )를 호출하면 Student라는 이름을 가진 함수를 만들고 함수 본문은 생성자 메소드 constructor에서 가져온다. 만약 생성자 메소드가 없으면 본문이 비워진 채로 함수가 만들어진다. 클래스 내에 정의한 메소드는 프로토 타입 객체에 저장
</aside>
< 해당 원리를 이용하여 클래스 문법과 유사하게 기능을 하는 생성자 함수를 사용 >
function Teacher(name) {
this.group = 14;
this.name = name;
}
Teacher.prototype.introduce = function() {
console.log(`안녕하세요 저는 ${this.group}강의실 교사 ${this.name}입니다.`);
}
let teacher = new Teacher("김유찬");
teacher.introduce();
<aside> 📌 **클래스와 생성자 함수의 차이점
</aside>
javascript에서도 java와 동일하게 상속(extens)를 사용할 수 있다.
< 부모 Class(상속을 해주는 Class) >
class Animal {
constructor(name, weight) {
this.name = name;
this.weight = weight;
}
eat(foodWeight) {
this.weight += foodWeight;
console.log(`${this.name}(은)는 ${foodWeight}kg의 식사를
하고 ${this.weight}kg이 되었습니다.`);
}
move(lostWeight) {
if(this.weight > lostWeight) this.weight -= lostWeight;
console.log(`${this.name}(은)는 움직임으로 인해
${lostWeight}kg 감량되어 ${this.weight}kg이 되었습니다.`);
}
}