Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 데이터전송
- HTTP
- 리눅스
- NextJS
- multer
- reactnative
- 개발공부
- scope
- docker
- Machine Learning
- 우선순위
- 1일1문장
- 끈기
- javascript
- 자료구조
- 러닝자바스크립트
- Linux
- Til
- Sequence
- ES6
- 스파르타코딩클럽
- 객체
- CSS
- coursera
- Andrew Ng
- 클로저
- nodejs
- 회고
- React
- 자바스크립트
Archives
- Today
- Total
해나아부지 개발일지
ES6 Class 와 Super 본문
JavaScript는 Prototype 기반의 언어이기 때문에 class라는 개념이 없었다. 사용자의 편의성을 위해 ES6(ECMA Script 2015)가 적용되고
작동원리는 똑같지만 class라는 키워드를 사용하여 조금 더 객체지향적으로 보이는 코딩을 할 수 있게 됐달까?
class
//ES5
function Car(model, company, year) {
this.model = model
this.company = company
this.year = year
}
Car.prototype.start = function () {
console.log(this.model + "가 출발합니다")
}
Car.prototype.stop = function () {
console.log(this.model + "가 정지합니다")
}
//ES6
class Car {
constructor(model, company, year) {
this.model = model
this.company = company
this.year = year
}
start() {
console.log(this.model + "가 출발합니다")
}
stop() {
console.log(this.model + "가 정지합니다")
}
}
new (생성자 함수)를 통해 인스턴스를 생성할 수 있고 결과는 같습니다.
딱 보기에도 객체지향적으로 보이고 가독성이 좋아진 것을 볼 수 있다.
super
기존의 Car보다 기능이 조금 더 업그레이드된 Car를 만들고 싶습니다. 코드를 다시 다 작성하기는 그렇고 기존 클래스에 새로운 기능 한두가지만 추가하고 싶습니다. 어떻게 하면 좋을까요 ?
ES5에서는 class를 상속받기 위해서 call or apply를 통해 상위클래스를 명시해줘야 했다. ES6에서는 'super()'라는 파워풀한 명령어로 해결이 되고 이조차도 생략할 수 있다.
//ES5
function UpgradeCar {
Car.prototype.call(this)
}
UpgradeCar.prototype = Object.create(Car.prototype)
UpgradeCar.prototype.constructor = UpgradeCar
UpgradeCar.prototype.autoDrive = function () {
console.log('자율주행을 시작합니다')
}
class UpgradeCar extends Car {
constructor() {
super()
} //생략 가능
//기존 메서드는 상속이 되고 새로운 메서드를 추가할 수 있다.
autoDrive() {
console.log("자율주행을 시작합니다")
}
'Developers > OOP' 카테고리의 다른 글
Object.create vs new #JavaScript (0) | 2020.07.31 |
---|---|
객체 지향 프로그래밍(OOP: Object-Oriented-Programming)이란? (0) | 2020.07.30 |
Comments