아래 코드를 클래스로 만들어서 중복을 없애보자
// 이를 클래스로 만들자
let studentA = {
name: "박정수",
grade: "A+",
age: 27,
study() {
console.log("열심히 공부 함");
},
introuduce() {
console.log("안녕하세요");
},
}
클래스
/**
*** 클래스**
*/
// 클래스에서는 쉼표를 안찍어도 됨
class Student {
// 필드
name;
grade;
age;
// 생성자
constructor(name, grade, age) {
this.name = name;
this.grade = grade;
this.age = age;
}
// 메서드
study() {
console.log("열심히 공부 함");
}
introuduce() {
console.log(`안녕하세요 ${this.name}`);
}
}
// 클래스를 이용해서 만든 객체 -> 인스턴스
// 스튜던트 인스턴드
let studentB = new Student("박정수", "A+", 26);
console.log(studentB);
studentB.study();
studentB.introuduce();
**// 중복 때문에 상속 받자**
class StudentDeveloper extends Student {
//필드
favoriteSkill;
// 생성자
constructor(name, grade, age, favoriteSkill) {
super(name, grade, age); // 부무 클래스의 생성자가 호출 됨
this.favoriteSkill = favoriteSkill;
}
// 메서드
programming() {
console.log(`${this.favoriteSkill}로 프로그래밍 함`);
}
}
const studentDeveloper = new StudentDeveloper("박정수", "B+", 26, "TypeScript");
console.log(studentDeveloper);
studentDeveloper.programming();