그냥 java, c++처럼 생성자 만들고,
this 써서 생성자 값 잘 넣고,
extends로 상속 잘하고,
자식 생성자에는 super(p1, p2, p3)로 부모 생성자 꼭 호출해주면 됨.
class Student {
name;
age;
grade;
constructor(name, grade, age) {
this.name = name;
this.grade = grade;
this.age = age;
}
}
constructor는 클래스에서 객체가 생성될 때 호출되는 함수다.(생성자)
this는 현재 만들어지고 있는 객체를 참조한다.
const studentB = new Student("홍길동", "A+", 27);
console.log(studentB);
// Student { name: '홍길동', age: 27, grade: 'A+' }
class Student {
name;
grade;
age;
constructor(name, grade, age) {
this.name = name;
this.grade = grade;
this.age = age;
}
study() {
console.log("열심히 공부 함");
}
introduce() {
console.log(`안녕하세요!`);
}
}
let studentB = new Student("홍길동", "A+", 27);
studentB.study(); // 열심히 공부 함
studentB.introduce(); // 안녕하세요!
class Student {
constructor(name, grade, age) {
this.name = name;
this.grade = grade;
this.age = age;
}
introduce() {
console.log(`안녕하세요 ${this.name} 입니다!`);
}
}
let studentB = new Student("홍길동", "A+", 27);
studentB.introduce(); // 안녕하세요 홍길동 입니다!
class StudentDeveloper extends Student {
}
StudentDeveloper는 Student를 확장(상속)한다.
부모 클래스의 필드와 메서드를 모두 자동으로 갖게 된다.
class StudentDeveloper extends Student {
favoriteSkill;
constructor(name, grade, age, favoriteSkill) {
super(name, grade, age); // 부모 클래스 생성자 호출
this.favoriteSkill = favoriteSkill;
}
programming() {
console.log(`${this.favoriteSkill}로 프로그래밍 함`);
}
}
super(...)는 부모 클래스의 생성자를 호출하는 키워드다.
자식 클래스 생성자에서 반드시 먼저 호출해야 한다.