자바스크립트애서 클래스 사용은 ES6에서부터 지원을 하기 시작했다. 최신 브라우저를 이용할 경우 class를 지원한다.
class를 사용하는 가장 큰 이유는 재사용성이다.
Js 내에서 class를 생성하려면 간단하다. class를 선언만 해준다면 class 객체를 바로 만들 수 있다
class Person {
}
let kim = new Person()
constructor(생성자)를 이용하면 class 객체의 초기 값을 설정해 줄 수 있다. class 내부에서 Contructor는 한 개만 존재할 수 있으며, 2번이산 사용시 error가 발생할 수 있다.
class Person{
construtor(name, age, city){
this.name = name;
this.age = age;
this.city = city
}
let yang = new Person('yang', 23, 'busan')
constructor는 새로운 클래스를 생성할 때 가장 처음 실행되면서 초기값을 설정해준다.
class에서 설정한 초기값을 접근해 특정 기능을 하는 메서드를 만드는 것도 가능하다.
class안에 function 형식으로 만들어준 뒤 해당 메서드를 호출하기만 하면 된다.
class Person{
construtor(name, age, city){
this.name = name;
this.age = age;
this.city = city
}
nextYearAge() { // getter 함수는 항상 return을 적어야된다.
return this.age + 1
let yang = new Person('yang', 23, 'busan')
console.log(yang.nextYearAge());
class에서 상속 개념을 이용할 수 있다. 상속이라고 단어를 어렵게 정의해놓아서 그렇지 쉽게 생각해보면 다른곳에 똑같은 class가 필요할때 복사(?)의 개념이라고 생각하면 쉽다. 즉, 기존의 class 값을 모두 접근하여 사용할 수 있다. 상속은 extends를 써서 이용할 수 있다.
super라는 키워드는 객체의 부모가 가지고 있는 메서드를 호출할 수 있다. 자식요소에 추가적으로 사용할 초기값이 필요할 경우 constructor에 super로 부모 초기값을 세팅한 뒤 자식 class에서만 사용할 초기값을 따로 지정하는 것도 가능하며 super 기능을 기용해서 자식 class에서 부모 메서드를 호출할 수도 있다.
class Person{
construtor(name, age, city){
this.name = name;
this.age = age;
this.city = city
}
nextYearAge() { // getter 함수는 항상 return을 적어야된다.
return this.age + 1
class Person2 extends Person {
constructor(name, age, city)
super(name, age, city)
this.gender = gender
}
let yang = new Person('yang', 23, 'busan')