
알고있으면 좋은 Javascript Tip✨
Class란 무엇인가?
- Javascript의 class는 객체(Object)와 관련이 있다.
- 쉽게 말해, 클래스는 객체를 생성하기 위한 템플릿이다. 객체를 직접 작성하여 정의하고 생성할 수도 있지만, 클래스로 만들어주면 여러 객체를 더 쉽게 만들 수 있다.
(1) Class를 사용하는 이유는?
- Class를 사용하는 가장 큰 이유는 재사용성이다. 작은 사이트의 경우 잘 만든 Function하나로도 충분히 개발이 용이했다면 좀 더 복잡한 사이트를 만들게 될 경우 Class의 장점을 더 잘 알 수 있다.
(2) Class 기본 문법
- Person이라는 이름의 객체가 생성된 걸 확인할 수 있다.
class Person {}
let user = new Person();
// Person{}
console.log(user);
(3) Class 초기값 설정
- Constructor(생성자)를 이용하면 class 객체의 초기 값을 설정해 줄 수 있다.
- class 내부에서 Constructor는 한 개만 존재할 수 있다.
- 2번 이상 사용 시 Syntax Error가 발생할 수 있다.
class Person {
constructor (name,age, city) {
console.log('construtor');
this.name = name;
this.age = age;
this.city = city;
}
}
let user = new Person('Alex','28','ohio');
// Person {name : 'Alex', age : 28, city : 'ohio'}
console.log(user);
(4) Class 메서드 추가
- Class 내부에 함수를 정의하면 메서드라고 불린다.
class Person {
constructor (name,age, city) {
console.log('construtor');
this.name = name;
this.age = age;
this.city = city;
}
// 메서드 생성
nextYearAge() {
return Number(this.age) + 1;
}
}
let user = new Person('Alex','28','ohio');
// 29
console.log(user.nextYearAge());
(5) 상속(extends)
- 상속을 통해 기존의 class의 값 모두 접근하여 사용할 수 있다.
class Person {
constructor (name,age, city) {
console.log('construtor');
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} 입니다.`
}
}
let user = new Person('Alex','28','ohio');
// 저는 ohio에 사는 Alex 입니다.
console.log(user.introduce());
(6) super
- 부모 클래스의 값을 상속받고, 추가적으로 자식만의 값을 사용하고싶다면 super 키워드를 사용할 수 있다.
- 자식 쪽에서 추가적으로 사용할 초기값이 필요할 경우 constructor에 super로 부모 초기값을 세팅한 뒤, 자식 class에서만 사용할 초기값을 따로 지정하는 것도 가능하고 super 기능을 이용해서 자식 class에서 부모 메서드를 호출할 수도 있다.
class Person {
constructor (name,age, city) {
console.log('construtor');
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.name} 입니다.
내년엔 ${super.nextYearAge()}살이며, 장래희망은 ${this.futureHope} 입니다.`
}
}
let user = new Person('Alex','28','ohio', 'baseball player');
// 저는 ohio에 사는 Alex 입니다. 내년에 29살이며, 장래희망은 야구선수 입니다.
console.log(user.introduce());'Study > JavaScript' 카테고리의 다른 글
| [JS] Early Return (0) | 2023.11.20 |
|---|---|
| [JS] undefined & null (0) | 2023.10.26 |
| [JS] getBoundingClientRect (0) | 2023.10.19 |
| [JS] toFixed (0) | 2023.10.19 |
| [JS] padStart & padEnd (0) | 2023.10.17 |