12.29.목(JS class)

유희선·2022년 12월 29일
0

TIL

목록 보기
8/29

1. Class
-하나의 클래스를 통해 동일한 구조를 갖는 여러 객체 생성
-하나의 설계도를 통해 여러 제품 생성 가능


2. 기본구조
1) class 생성
2) class를 통한 객체 생성

class 클래스이름(shirt) {
    // 여러 메서드 정의 가능
    constructor (color, size, property) {
        this.color = 'white',
        this.size = 95,
        this.property = 'loose'
    }

    //실행하고 싶은 함수
    Print1() {
        console.log(`shirt 정보는 다음과 같습니다. [color : ${this.color}, size : ${this.size}, property : ${this.property}]`)

    }    
}

//사용법
//'새로운 변수 = new shirt()'를 생성해서 '전체값.호출하고 싶은 함수()' 입력
const shirt1 = new shirt()
shirt1.Print1()

3) 더 간단한 표현법
*변수 이름을 class에 직접 넣을 수 있음

const shrit1 = class 클래스이름(shirt) {
    // 여러 메서드 정의 가능
    constructor (color, size, property) {
        this.color = 'white',
        this.size = 95,
        this.property = 'loose'
    }

    //실행하고 싶은 함수
    Print1() {
        console.log(`shirt 정보는 다음과 같습니다. [color : ${this.color}, size : ${this.size}, property : ${this.property}]`)

    }    
}

//사용법
new shirt1.Print1()

3. class 표현식
-함수처럼 클래스도 다른 표현식 내부에서 정의,전달,반환,할당 가능
1) Named Function Expression (기명 함수 표현식)
-클래스 표현식에 이름을 붙이면,
이 이름은 오직 클래스 내부에서만 사용할 수 있음

// 기명 클래스 표현식(Named Class Expression)
// (명세서엔 없는 용어이지만, 기명 함수 표현식과 유사하게 동작합니다.)
let people = class introduce {
  sayHi() {
    alert(introduce); 
    // introduce라는 이름은 오직 클래스 안에서만 사용할 수 있습니다.
  }
};

new people().sayHi(); // 원하는대로 MyClass의 정의를 보여줍니다.

alert(introduce); 
// ReferenceError: MyClass is not defined, MyClass는 클래스 밖에서 사용할 수 없습니다.

2) 아래와 같이 '필요에 따라' 클래스를 동적으로 생성 가능

function makeClass(phrase) {
  // 클래스를 선언하고 이를 반환함
  return class {
    sayHi() {
      alert(phrase);
    };
  };
}

// 새로운 클래스를 만듦
let people = makeClass("안녕하세요.");

new people().sayHi(); // 안녕하세요.

4. getter와 setter
1) 개념 > 예외처리
-'literal을 사용해 만든 객체'처럼
클래스도 getter, setter, 계산된 프로퍼티(computed property)를 지원함
-get, set을 이용해 user.name을 조작할 수 있음

class User {
  constructor(name) {
    // setter를 활성화합니다.
    this.name = name;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    if (value.length < 4) {
      alert("이름이 너무 짧습니다.");
      return;
    }
    this._name = value;
  }
}

let user = new User("보라");
alert(user.name); // 보라

user = new User(""); // 이름이 너무 짧습니다.

2) setter를 추가한 순간
-값을 할당하려고 시도하면,
프로퍼티의 값에 직접 할당하지 않고 setter값 호출
3) getter를 추가한 순간
-값을 사용하려고 시도하면,
메모리에 저장된 값이 불러오지 않고 getter값 호출


5. 클래스 필드로 바인딩 된 메서드 만들기
1) 해당코드 출력값 = undefined

class Button {
  constructor(value) {
    this.value = value;
  }

  click() {
    alert(this.value);
  }
}

let button = new Button("안녕하세요.");

setTimeout(button.click, 1000); // undefined

2) '1)'과 같은 상황이 발생한 이유
-this의 컨텍스트를 알 수 없게 되서 생긴 문제
='잃어버린 this(losing this)'
-문제를 해결할 수 있는 방법 => 함수 바인딩

  1. setTimeout(() => button.click(),1000) 같이 래퍼 함수 전달하기
  2. 생성자 안 등에서 메서드를 객체에 바인딩하기

3) 수정코드

class Button {
  constructor(value) {
    this.value = value;
  }
  click = () => {
    alert(this.value);
  }
}

let button = new Button("안녕하세요.");

setTimeout(button.click, 1000); // 안녕하세요.

6. 요약

class MyClass {
  prop = value; // 프로퍼티

  constructor(...) { // 생성자 메서드
    // ...
  }

  method(...) {} // 메서드

  get something(...) {} // getter 메서드
  set something(...) {} // setter 메서드

  [Symbol.iterator]() {} // 계산된 이름(computed name)을 사용해 만드는 메서드 (심볼)
  // ...
}

0. 링크
https://ko.javascript.info/class

0개의 댓글