티스토리 뷰

Class 

 

* class와 object

 

1. class 

- object(인스턴스)를 만들 수 있는 틀이다.

- class 자체에는 data가 들어있지 않다.

- 틀을 정의해서 한번만 선언한다.

- class는 정의만 한 것이기 때문에 실제 메모리에 올라가지 않는다.

 

2. object

- class를 이용해 data를 넣어 만드는 것이다.

- class를 이용해 새로운 인스턴스를 생성하면 그게 바로 object이다.

- object는 class를 이용해서 무수히 많이 만들 수 있다.

- class를 이용해 만든 object는 실제 메모리에 올라간다.

 


1. class 선언과 object 생성

class Person {
  //constructor
  constructor(name, age) {
    //fields
    this.name = name;
    this.age = age;
  }

  //methods
  speak() {
    console.log(`${this.name}: hello~`);
  }
}

const ellie = new Person("ellie", 24); // 인스턴스 생성 (object)
console.log(ellie);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();

결과

 

2. Getter / Setter

 

getter 함수는 특정 값을 조회할 때 내가 설정한 함수로 연산된 값을 반환한다.

class User {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  // getter
  get age() {
    return this._age;
  }

  //setter
  set age(value) {
    this._age = value < 0 ? 0 : value;
  }
}

const user1 = new User("steve", "job", -10);
console.log(user1.age);

 

3. 상속

// 부모 class
class Shape {
  constructor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
  }

  draw() {
    console.log(`drawing ${this.color} color of`);
  }

  getArea() {
    return this.width * this.height;
  }
}

class Rectangle extends Shape {}
class Triangle extends Shape {
  draw() {
    super.draw(); // super을 앞에 써주면 오버라이딩 해도 부모 class 메소드 호출 가능
    console.log(`△`);
  }

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

const rectangle = new Rectangle(20, 20, `blue`);
rectangle.draw();
console.log(rectangle.getArea());

const triangle = new Triangle(20, 20, `red`);
triangle.draw();
console.log(triangle.getArea());
댓글