드림코딩 자바스크립트 프론트엔드 개발자 입문편 (JavaScript ES5+)을 공부하며 정리한 학습노트 입니다.
Class가 가진 상속과 다양성의 성질은 Class내에서 공통적으로 쓰이는 속성 값을 재사용 가능하게 한다. 이러한 특징은 유지보수를 편리하게하며, 같은 코드를 반복하여 작성하지 않아도 되는 장점이 있다.
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing $(this.color) color!`);
}
getArea() {
return this.width * this.height;
}
}
Shape라는 Class를 만들고 생성자를 이용해 메서드에 사용할 width, height, color의 값을 전달했다. 그리고 draw()와 getArea() 라는 메서드를 선언하였다.
이것을 이용해 직사각형에 대한 Class를 정의하고 싶다면 상속을 이용할 수 있다.
class Rectangle extends Shape {}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
extends
라는 키워드를 이용해 shape에서 정의한 것들이 자동적으로 포함시킨다. 이처럼 상속을 이용하면 공통되는 것을 일일히 작성하지 않고 재사용가능하다.
extends
키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class식에 사용된다.- syntax
class ChildClass extends ParentClass { ... }
만약 class Shape를 이용해 삼각형을 정의하고 싶다면 OverWriting을 이용할 수 있다.
class Triangle extends Shape {
getArea() {
return (this.width * this.height) / 2;
}
}
삼각형의 너비를 구할때 너비 * 높이 / 2 이기 때문에 getArea()를 extends
로 재정의하면 코드를 반복해서 작성하지 않고 필요한 부분만 재정의하여 사용할 수 있다.
또한 부모에게 물려받은 공통으로 정의된 메서드도 사용하며 동시에 OverWriting 하는 것도 가능하다.
class Triangle extends Shape {
draw() {
super.draw();
console.log('triangle!');
}
}
const triangle = new Triangle(20, 20, 'red');
위 코드는 Shape Class를 상속받은 Triangle Class에서 super
키워드를 이용해 부모 함수를 호출하고 콘솔에 텍스트를 뿌리는 console.log('triangle!'); 도 추가한 것이다.
콘솔을 확인하면 drawing red color! 와 triangle! 모두 출력되는 것을 볼 수있다.
super
키워드는 부모 오브젝트의 함수를 호출할 때 사용됩니다.- syntax
super([arguments]); // 부모 생성자 호출
super.functionOnParent([arguments]);
instanceOf
를 이용해 만들어진 instance가 무엇을 상속하는지 이해할 수 있는 간단한 퀴즈를 풀어보자!
instanceof
연산자는 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별한다.- syntax
object instanceof constructor
console.log(rectangle instanceof Rectangle); //t
console.log(triangle instanceof Rectangle); //f
console.log(triangle instanceof Triangle); //t
console.log(triangle instanceof Shape); //t ,Shape을 상속함
console.log(triangle instanceof Object); //t,JS에 만든 모든 class는 JS object를 상속함
console.log(triangle.toString()); //어떤 오브젝트던지 공통적으로 존재하는 메서드를 사용할 수 있다.
toString()과 같은 문자열화 메서드도 JS object를 상속하기 때문에 OverWriting하여 사용하는 것이 가능하다.
[참고]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/super
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/extends