해나아부지 개발일지

ES6 Class 와 Super 본문

Developers/OOP

ES6 Class 와 Super

__APPA 2020. 8. 1. 23:48

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 + "가 정지합니다")
  }
  
}

class Car의 인스턴스

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("자율주행을 시작합니다")
}

class 상속

 

 

Comments