[JS] Class 생성 및 상속

J.A.Y·2024년 1월 29일
0

javaScript

목록 보기
11/21

함수 형태의 클래스는 보통 자바에서 많이 사용하고, 자바스크립트에서는 객체를 많이 사용한다고 합니다. 그래도 코드를 봤을 때 이해할 수 있어야 하니 배워보겠습니다.

기본 문법

함수형 클래스를 정의하는 JS 문법은 다음과 같습니다.

class 클래스명 {
	constructor() {
   }
}

constructor:

  • 함수형 클래스 안에 객체를 생성하고 초기화해주는 메서드입니다.
  • 단 한번만 사용될 수 있고, 중복으로 작성하면 문법 오류가 발생합니다.

❗함수형 클래스는 일반 함수와 달리 정의를 먼저 해준 뒤에야 호출이 가능합니다.❗

예제

class Fruit {
    constructor(name, cost) {
        this.name = name;
        this.cost = cost;
    }
}

let fruit1 = new Fruit("Apple", 2300);
let fruit2 = new Fruit("Pear", 3500);
let fruit3 = new Fruit("Watermelon", 10000);

console.log(fruit1, fruit2, fruit3);
// Fruit { name: 'Apple', cost: 2300 } Fruit { name: 'Pear', cost: 3500 } Fruit { name: 'Watermelon', cost: 10000 }

함수를 넣어 활용하는 법

함수형 클래스 안에 추가로 함수를 만들어 활용할 수 있습니다.
예시

class Shape {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    getArea() {
        return this.width * this.height;
    }
}

let rec = new Shape(3, 4);
console.log(`직사각형 넓이: ${rec.getArea()}cm^2`);

상속: extends와 super

이 둘은 기존 클래스를 새로운 클래스에 상속시키고, 추가로 다른 것들을 덧붙이고 싶을 때 사용합니다.

예시1

class Rectangle extends Shape {
    constructor(width, height) {
        super(width, height);
    }
    getDigonal() {
        return Math.sqrt(Math.pow(this.width, 2) + Math.pow(this.height, 2));
    }
}

rec = new Rectangle(3, 4);
console.log(`직사각형 대각선 길이: ${rec.getDigonal()}cm`);
// 직사각형 대각선 길이: 5cm

예시2

class Triangle extends Shape {
    constructor(width, height) {
        super(width, height); //call super constructor in derived class
    }
    getArea() {
        return (this.width + this.height) * 0.5;
    }
}

let tri = new Triangle(3, 4);
console.log(`삼각형 넓이: ${tri.getArea()}cm^2`);
// 삼각형 넓이: 3.5cm^2

예시3

class Circle extends Shape {
    constructor(radius) {
        super(radius);
        this.radius = radius;
    }
    getArea() {
        return Math.PI * Math.pow(this.radius, 2);
    }
}

let circle = new Circle(3);
console.log(`원 넓이: ${circle.getArea()}`);
// 원 넓이: 28.274333882308138
profile
Done is better than perfect🏃‍♀️

0개의 댓글