자바스크립트 클래스 상속 질문드립니다.

자바스크립트 클래스 상속 질문드립니다.

작성일 2021.08.14댓글 1건
    게시물 수정 , 삭제는 로그인 필요

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

class Rectangle extends Shape {}
class Triangle extends Shape {
draw() { // super상속 및 오버라이딩
console.log(`${super.draw()} 삼각형`);
}

getArea() { // 오버라이딩
return (this.width * this.height) / 2;
}
}

const rectangle = new Rectangle(10,10,'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(10,10,'red');
triangle.draw();
console.log(triangle.getArea());

출력 결과:

drawing blue color!
100
drawing red color!
undefined 삼각형
50


삼각형을 draw하는 부분에서 출력 결과가

drawing red color!

undefined 삼각형


이렇게 나옵니다. 



drawing red color! 삼각형


이렇게 한줄로 나오게 하고 싶은데 어떻게 해야할까요??




#자바스크립트 클래스 #자바스크립트 클래스 추가 #자바스크립트 클래스 쓰는 이유 #자바스크립트 클래스 가져오기 #자바스크립트 클래스 상속 #자바스크립트 클래스 선택자 #자바스크립트 클래스 호출 #자바스크립트 클래스 확인 #자바스크립트 클래스 private #자바스크립트 클래스 생성자

profile_image 익명 작성일 -

draw 메소드에서 값을 출력하지 않고, return 문으로 메소드를 호출한 곳에 값을 반환합니다.

rectangle.draw(); 는 console.log(rectangle.draw());로 바꿔주세요.

draw() { return `drawing ${this.color} color!`; } // 생략 console.log(rectangle.draw());

전체 코드

class Shape { constructor(width, height, color) { this.width = width; this.height = height; this.color = color; } draw() { return `drawing ${this.color} color!`; } getArea() { return this.width * this.height; } } class Rectangle extends Shape {} class Triangle extends Shape { draw() { // super상속 및 오버라이딩 console.log(`${super.draw()} 삼각형`); } getArea() { // 오버라이딩 return (this.width * this.height) / 2; } } const rectangle = new Rectangle(10,10,'blue'); console.log(rectangle.draw()); console.log(rectangle.getArea()); const triangle = new Triangle(10,10,'red'); triangle.draw(); console.log(triangle.getArea());

자바스크립트 클래스 상속 질문

... super상속 및 오버라이딩 console.log(`${super.... super상속 및 오버라이딩 console.log(`${super.... class Triangle extends Shape { draw() { // super상속...

자바스크립트 상속 관련 질문

자바스크립트 공부하면서 상속의 개념에 대해 공부했는데 상속을 하는 근본적인 이유는... 이렇게 부모 클래스의 속성과 메서드를 상속받은 자식 클래스는 중복된 코드를...

자바스크립트 상속 질문

안녕하세요 자바스크립트를 혼자 공부하는데요, 상속이 헷갈립니다.... 상속을 구현 할 때 클래스가 아닌, classical 한 방법으로 구현할 때의...

js 자바스크립트 클래스 질문

/* Q3) Student 클래스를 extends한 FeStudent... 메소드를 상속받습니다. study 메소드는 'Let... 도움되셨다면 채택 부탁드립니다~! class...

유니티 클래스 상속 질문

코린이라 기본지식 부족한 점 양해드립니다!! 클래스 상속 받을 때 1) public... 질문자님, 안녕하세요! 유니티 클래스 상속에 대한 궁금증을...

자바스크립트 질문드립니다.

jsp에서 저장 초기화 이렇게 jsp가 구성되어 있고, 수정버튼을 클릭하면 class="hide"에 클래스 추가가되어서 2개의 버튼이 노출되는 기능입니다. 2개만 적었지만...