190923 ES6 -class

zenibako.lee
3 min readSep 23, 2019

--

class는 es6 이전버젼에서는 없는 키워드이지만, function을 이용해 유사한 방식으로 사용이 가능했다.

es6이후로는 ‘extends’를 이용해 상속을 받거나, instance를 보다 간편하게 생성할 수 있게 되었다.

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++ }
}

이러한 형태를 보인다.

외관상의 차이점은,

1.function이 아닌 class type으로 선언을 하고

2.property, method간에 ‘ , ’ 를 쓰지 않는다.

static

class Car { constructor () {
this.topSpeed = Math.random()
}
static isFaster (left, right) { // static method
return left.topSpeed > right.topSpeed
}
}

그리고 static이라는 메소드 앞에 접두어가 사용 가능하다.

이 경우, Car의 생성자를 이용해 만들어진 객체들은 해당 메소드에 접근조차 할 수 없다.

오히려 Car.isFaster(instance1,instance2)와 같이, 객체들을 parameter로 넣어서 사용한다.

이는 원본 class의 오염가능성을 방지할 수 있다.

extends

class Car {
constructor (speed) {
this.speed = speed
}
}
class Tesla extends Car {
constructor (speed) {
super(speed * 2)
}
move () {
super.move()
this.distance += 4
}
}

extends를 통해 Tesla라는 클래스는 Car클래스를 상속받는다.

이 때, super를 이용해 부모의 메소드를 불러와서 override를 할 수 있다. 부모에는 영향이 가지 않는다.

move()의 경우 부모의 move()를 호출하는데, Car.move()는 존재하지 않으므로, 오류이다

--

--

zenibako.lee
zenibako.lee

Written by zenibako.lee

backend engineer, JS, Node, AWS

No responses yet