[Javascript] 자바스크립트에서 Class(클래스) 사용법
자바스크립트에서 클래스(class) 사용은 ES6에서부터 지원을 하기 시작했다.
익스플로러에서는 해당 코드 사용이 불가능하나, 대부분의 최신 브라우저를 이용할 경우 class를 지원한다.
클래스 상속(class inheritance, subclassing) 기능을 통해 한 클래스의 기능을 다른 클래스에서 재사용할 수 있다.
이제 클래스의 기본 사용법에 대해서 알아보자!
Class 생성 방법
Javascript 내에서 Class를 생성 방법은 간단하다.
class를 선언만 해준다면 class 객체를 바로 만들 수 있다.
class Person {
}
let hong = new Person();
console.log(hong);
class로 만들어준 예시인 Person이라는 이름의 객체가 생성된 걸 확인할 수 있다.
Class 초기값 설정법
Constructor(생성자)를 이용하면 class 객체의 초기 값을 설정해 줄 수 있다.
class 내부에서 Constructor는 한 개만 존재할 수 있으며, 2번 이상 사용 시 Syntax Error가 발생할 수 있다.
Constructor를 이용하여 Person 클래스에 초기 값을 설정해보도록 하자.
class Person {
//초기값설정
constructor (name,age, city) {
console.log('construtor');
this.name = name;
this.age = age;
this.city = city;
}
}
let hong = new Person('hong','20','seoul');
console.log(hong);
Constructor는 새로운 클래스를 생성할 때 가장 처음 실행되면서 초기값을 설정해준다.
class 메서드 생성
class에서 설정한 초기값을 접근해 특정 기능을 하는 메서드를 만드는 것도 가능하다.
class안에 function 형식으로 만들어준 뒤 해당 메서드를 호출하기만 하면 된다.
또는
class는 javascript 상 객체의 형태이므로 생성된 class 객체에 class 밖에서 새로운 메서드를 넣는 것도 가능하다.
class Person {
//초기값 설정
constructor (name,age, city) {
this.name = name;
this.age = age;
this.city = city;
}
//메서드 생성
nextYearAge() {
return Number(this.age) + 1;
}
}
let hong = new Person('hong','20','seoul');
//class 밖에서 새로운 메서드 생성
hong.eat = function () {
return 'jelly'
}
console.log('hong.nextYearAge() : ' + hong.nextYearAge());
console.log('hong.eat() : ' + hong.eat());
console.log(hong);
class 안/밖에서 추가한 메서드가 잘 작동된 걸 볼 수 있다.
하지만, eat메소드처럼 밖에서 추가한 class는 추후 새로운 new class로 새로운 객체를 만들었을 때는 호출하여 사용할 수 없다.
class Person {
//초기값 설정
constructor (name,age, city) {
this.name = name;
this.age = age;
this.city = city;
}
//메서드 생성
nextYearAge() {
return Number(this.age) + 1;
}
}
let hong = new Person('hong','20','seoul');
//class 밖에서 새로운 메서드 생성
hong.eat = function () {
return 'jelly'
}
console.log('hong.nextYearAge() : ' + hong.nextYearAge());
console.log('hong.eat() : ' + hong.eat());
console.log(hong);
//새로운 객체생성
let park = new Person('park', '30', 'busan');
console.log(park);
console.log('park.nextYearAge() : ' + park.nextYearAge());
console.log('park.eat() : ' + park.eat()); //메소드가 없어서 에러
이처럼 새로운 객체에는 eat이라는 메서드가 선언되지 않아서 위와 같이 메서드가 없다고 에러가 나온다.
eat이라는 메소드는 hong객체에서만 사용할 수 있는 메서드라고 생각하면 된다.
상속(extends)
class에서 상속 개념을 이용할 수 있습니다.
css를 이용한 분들이라면 하나의 속성이 하위 속성에도 같이 적용되는 것처럼
class에서도 상속을 이용하면 기존의 class의 값을 모두 접근하여 사용할 수 있다.
상속은 extends를 써서 이용할 수 있다.
class Person {
//초기값 설정
constructor (name,age, city) {
this.name = name;
this.age = age;
this.city = city;
}
//메서드 생성
nextYearAge() {
return Number(this.age) + 1;
}
}
//상속 클래스
class introducePerson extends Person {
introduce () {
return `저는 ${this.city}에 사는 ${this.name}살 ${this.name} 입니다.`
}
}
let hong = new introducePerson('hong','20','seoul');
console.log('결과 : ' +hong.introduce());
예제를 통해서 introducePerson클래스에서 Person을 상속받았기 때문에
this.city, this.name, this.name을 모두 사용할 수 있는 것을 확인할 수 있다.
super 사용하기
상속해서 하위 클래스에서 기존 class의 값을 가져다 쓰는 건 좋았지만,
추가적으로 상속한 하위 클래스에서만 사용하고 싶은 값이 있을 수도 있다.
이때 이용하는 것은 super라는 키워드이며 객체의 부모가 가지고 있는 메서드를 호출할 수 있다.
자식 쪽의 추가적으로 사용할 초기값이 필요할 경우 constructor에 super로 부모 초기값을 세팅한 뒤
자식 class에서만 사용할 초기값을 따로 지정하는 것도 가능하며
super 기능을 이용해서 자식 class에서 부모 메서드를 호출할 수도 있다.
class Person {
//초기값 설정
constructor (name,age, city) {
this.name = name;
this.age = age;
this.city = city;
}
//메서드 생성
nextYearAge() {
return Number(this.age) + 1;
}
}
//상속 클래스
class introducePerson extends Person {
constructor(name, age, city, futureHope) {
super(name, age, city);
this.futureHope = futureHope
}
introduce () {
return `저는 ${this.city}에 사는 ${this.age}살 ${this.name} 입니다.
내년엔 ${super.nextYearAge()}살이며,
장래희망은 ${this.futureHope} 입니다.`
}
}
let hong = new introducePerson('hong','20','seoul','개발자');
console.log('결과 : ' +hong.introduce());
//예제결과
결과 : 저는 seoul에 사는 20살 hong 입니다.
내년엔 21살이며,
장래희망은 개발자 입니다.
오버라이딩
일반적인 객체지향 언어처럼 생성자 오버라이딩 혹은 메서드 오버라이딩을 할 수 있다.
오버라이딩이란 이미 정의된 메소드를 자식 클래스에서 같은 시그니쳐를 갖는 메소드로 다시 정의하는 것이다.
즉, 메서드 오버라이딩을 통해 아예 기능을 변경해버릴 수도 있다. 또는 super 없이 그냥 원하는 기능을 구현해주면 된다.
class Person {
//초기값 설정
constructor (name,age, city) {
this.name = name;
this.age = age;
this.city = city;
}
//메서드 생성
nextYearAge() {
return Number(this.age) + 1;
}
eat(){
return 'jelly'
}
}
//상속 클래스
class introducePerson extends Person {
constructor(name, age, city, futureHope) {
super(name, age, city);
this.futureHope = futureHope
}
introduce () {
return `저는 ${this.city}에 사는 ${this.age}살 ${this.name} 입니다.
내년엔 ${super.nextYearAge()}살이며,
장래희망은 ${this.futureHope} 입니다.`
}
//오버라이딩
eat(){
return super.eat()+'소화완료'
}
nextYearAge() {
return Number(this.age) + 10;
}
}
let hong = new introducePerson('hong','20','seoul','개발자');
console.log('결과 : ' +hong.introduce());
console.log('결과 : ' +hong.eat());
console.log('결과 : ' +hong.nextYearAge());
class를 이용할 경우 규칙성을 갖는 객체를 일관성 있게 만드는 게 가능하며, 상속을 통해서 기능 확장이 용이하다.
잘 활용하면 실무에 유용할 것 같다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes
Classes - JavaScript | MDN
Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의
developer.mozilla.org