자바스크립트는 원래 프로토타입 기반 객체지향 언어였다.
하지만 다른 클래스기반 언어(C++ ,Java등)에 익숙한 개발자들에게는 문법이 다소 낯설게 느껴졌고, 이를 보완하기 위해 Syntactic Sugar 형태로 클래스 문법이 추가되었다. (Syntactic Sugar - 문법적 설탕이란 기존에 가능했던 기능을 쉽고 보기좋게 표현할 수 있도록 제공된 문법)
그 결과, 더 직관적인 객체지향 프로그래밍(OOP)스타일을 지원할 수 있게 되었으며, 이 클래스 문법은 ES6 (ECMAScript 2015) 에서 처음 도입되었다.
아래 코드처럼 두 개의 객체를 직접 만들면, studentA와 studentB 사이에 중복되는 코드가 매우 많다는 것을 알 수 있다. 그래서 이런 중복을 줄이기위해 클래스를 만들어두면 훨씬 깔끔하고 편하게 객체를 만들 수 있다.
let studentA = {
name:'heesu',
grade: "A",
age: 27,
study(){
console.log('공부중')
},
instroduce(){
console.log('hi')
}
}
let studentB = {
name:'heesu2',
grade: "A",
age: 30,
study(){
console.log('공부중')
},
instroduce(){
console.log('hi')
}
}
클래스를 사용하면 직관적이고 쉽게 사용할 수 있다. *** 클래스는 파스칼 표기법을 쓴다.**
class Student {
// 필드
name;
grade;
age;
// 생성자
constructor(name, grade, age) {
// 매개변수로 받은 값들을 실제로 만들 객체의 프로퍼티의 값으로 설정한다.
this.name = name;
this.grade = grade;
this.age = age;
}
// 매서드
study (){
console.log('공부중')
}
instroduce(){
console.log(`hi ${this.name}입니다`)
}
}
클래스를 이용해서 만든 객체를 인스턴스라고 한다. 아래 studentC는 Student 인스턴스라고 부른다(student 클래스를 이용해서 만든 객체라는 뜻)
new를 붙혀서 클래스를 적고, 인수를 넘기게되면 클래스 내 생성자(constructor)를 호출한다.
let studentC = new Student('hi','A','27')
console.log(studentC) // Student(name:'hi',grade:'A',age:'27');
studentC.stude(); // 공부중
studentC.instroduce(); // hi hi입니다
extends 를 이용해서 부모로부터 상속받은 클래스를 만들 수 있다.
내부에는 super키워드를 이용해 부모클래스의 생성자를 호출해야한다.
class StudentDeveloper extends Student {
//StudentDeveloper 에 추가할 필드
favoriteSkill
constructor(name, grade, age, favoriteSkill){
// super 키워드를 이용해 부모클래스의 생성자를 호출한다.
super(name, grade, age)
this.favoriteSkill = favoriteSkill;
}
skill(){
console.log(`좋아하는 스킬은? ${this.favoriteSkill}`)
}
]
let studentD = new StudentDeeloper('hi','A','27','ts')
console.log(studentD)
// StudentDeveloper (name:'hi',grade:'A',age:'27',favoriteSkill :'ts');
studentD.skill()
// 좋아하는 스킬은? ts