본문 바로가기

Mini-Study

ES5 와 ES6의 상속 차이점

*Class(ES6)

: ES5의 일반 프로토 타입 상속 구문보다 훨씬 쉽게 작업 할 수 있다.

: 상위 클래스와 하위 클래스로 나뉜다.

: 하위 클래스는 상위 클래스의 속성을 상속받아 사용할 수 있다.

(이렇게 되면 상위 클래스 = 부모, 하위 클래스 = 자식이 된다.)

: 상위 클래스의 속성을 상속 받은 뒤 하위 클래스는 상속의 내용을 변경 할 수 있다. (하지만 상위 클래스의 속성은 변경되지 않는다.)

: 하위 클래스에 따로 속성을 추가 할 수 있다.

- ES5의 상속 방법(prototype)

function Car () {

this.fuel = 0;

this.distance = 0;

}

Car.prototype.move = function () {

if (this.fuel < 1) {

throw new RangeError('Fuel tank is depleted')

}

this.fuel--

this.distance += 2

}

Car.prototype.addFuel = function () {

if (this.fuel >= 60) {

throw new RangeError('Fuel tank is full')

}

this.fuel++

}

: 사용하기 위해선 다음과 같은 방법으로 사용

function Tesla() {

Car.call(this)

}

Tesla.prototype = Object.prototype(Car.prototype)

Tesla.prototype.constructor = Tesla

​

var car = new Car()

car.addFuel()

car.move()

car.move()

// <- RangeError: 'Fuel tank is depleted'

-ES6의 상속 방법(class)

class Car {

constructor () {

this.fuel = 0

this.distance = 0

}

move () {

if (this.fuel < 1) {

throw new RangeError('Fuel tank is depleted')

}

this.fuel--

this.distance += 2

} addFuel () {

if (this.fuel >= 60) {

throw new RangeError('Fuel tank is full')

}

this.fuel++

}

}

:사용하기 위해선 다음과 같은 방법으로 사용

class Tesla extends Car {

move () {

super.move()

this.distance += 4

}

}

​

var car = new Tesla()

car.addFuel()

car.move()

이와 같이 prototype 형식의 상속은 상위객체를 상속 받을려면 하위객체마다 Object.create()를 해줘야하기 때문에 번거로움과 시간이 오래걸린다는 점이 있지만 class 형식의 상속은 번거로움 없이 extends라는 키워드를 통해 쉽고 간단하게 상속을 할 수 있다.

'Mini-Study' 카테고리의 다른 글

S3, EC2, RDS  (0) 2020.02.05
React  (0) 2020.02.05
browser, server, api, http, ajax  (0) 2020.02.05
Stack, Queue, Linked List란?  (0) 2020.02.05
Tree, Graph, Hash Table, Binary Search Tree 란?  (0) 2020.02.05