JavaScript 기초(class)

Sujeong K·2022년 7월 21일
0

JavaScript_basic

목록 보기
7/17

Class

  • 연관있는 데이터(변수, 함수)들을 묶어놓은 container
  • 객체를 생성하기 위한 templete
class person{
name;
age;
speak();
}
  • 구성 요소: 속성(field), 행동(method)
  • class를 이용해서 새로운 instance를 생성하면 Object가 됨

class 선언

class Person{
  //constructor
  constructor(name, age) {
    //fields
this.name = name;
this.age = age;
}
  //methods
  speak() {
    console.log(`${this.name} hello!`);
  }
}

  const jane = new Person('jane', 20); // new 생성자로 Object 생성
  console.log(jane.name); // 'jane' 출력
  jane.speak(); // 'jane hello!' 출력

접근자 프로퍼티(accessor property)

  • 접근자 프로퍼티의 본질은 함수
  • 값을 획득(get)하고 설정(set)하는 역할을 담당
  • 외부 코드에서는 함수가 아닌 일반적인 프로퍼티처럼 보임
class User{
    constructor(name, age) {
  this.name = name;
  this.age = age;
  }
  get age() {
    return this.age; // age를 호출하면 바로 this.age를 반환
  }
  set age(value) {
     this.age = value < 0 ? 0 : value;
  } // 새로운 value를 받으면 this.age에 할당해줌
  }
const user1 = new User('jane', 10);
console.log(user1.age);
  • age는 접근자 프로퍼티.
  • get age() : 값 가져오기. this.age를 사용할 때 실행되며 this.age 값을 리턴함
  • set age(value) : 값 설정하기. this.age에 값을 할당할 때 실행, 매개변수로 value 받아와야함
  • 접근자 프로퍼티를 사용하면 함수를 호출하지 않고 user1.age 형식으로 일반 프로퍼티에서 값에 접근하는 것과 같이 프로퍼티 값을 얻을 수 있음
  • 사용자가 입력한 값이 잘못된 경우를 대비해 Set을 사용해서 값을 할당해주기

❌ 에러 발생
user1객체를 만들면서 age에 값을 할당하려함 -> set age(value)를 호출
이후 삼항연산자를 거친 후 this.age에 value를 할당하려함 -> set age(value)를 호출
또 삼항연산자를 거친 후 this.age에 value를 할당하려함 -> set age(value)를 호출

console.log(user1.age); 코드로 this.age를 사용하려함 -> get age()를 호출
this.age를 리턴하려고 this.age를 사용하려함 -> get age()를 호출
또 this.age를 리턴하려고 this.age를 사용하려함 -> get age()를 호출

무한반복..

class User{
    constructor(name, age) {
      //fields
  this.name = name;
  this.age = age;
  }
  get age() {
    return this._age; 
  }
  set age(value) {
    this._age = value < 0 ? 0 : value;
  } 
  }
  
const user1 = new User('jane', 10);
console.log(user1.age);
  • getter와 setter 내부의 this.agethis._age로 변경
    *underscore(__)는 private, 내부적인 속성이라는 뜻이며 이렇게 만든 프로퍼티는 외부에서 접근이 가능하지만 외부에서 사용하지는 않음
  • User라는 class 안에는 name, _age 총 2개의 field가 존재
  • field는 _age이지만 this.age로 호출하고 할당할 수 있는 것은 getter와 setter를 이용하기 때문!

상속과 다양성

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 {}
  • extends 키워드를 이용해서 Shape class의 fields와 methods를 Rectangle에 상속해줌(RectangleShape의 자식 class)
  • 부모 class에서 수정된 fields나 methods는 자식 class에서 자동으로 수정됨

📌 자식 class에서 필요한 부분만 재정의하기(overriding)

class Triagle extends Shape {
    getArea(){
        return (this.width * this.height) / 2;
    }
}

📌 super 키워드로 부모 class에 접근하기

class Triagle extends Shape {
    draw(){
      super.draw(); // Shape class의 draw 메서드를 호출
      console.log('triagle!');
    }
}

instanceof 연산자

  • instanceOf 왼쪽에 있는 class가 오른쪽에 있는 class의 instance인지 판별함
  • Boolean 반환
console.log(rectangle instanceof Rectangle); // true
console.log(rectangle instanceof Shape); // true
console.log(rectangle instanceof Object); // true

*JS에서 만들어진 모든 class는 Object라는 객체를 상속한 것

profile
차근차근 천천히

0개의 댓글