[JS] 클래스

Local Gaji·2023년 5월 10일

JavaScript

목록 보기
4/18

0. 생성자

  • 객체를 생성하는 함수
  • 여러개의 동일한 property를 가지는 객체를 생성하기 위해 필요
    • 메모리 절감 효과

const 객체명 = new 클래스명(인수)

// 클래스 선언하기
function User (country, city) {
  this.country = country;
  this.city = city;
}  

// User 클래스의 프로퍼티를 가지는 객체 생성 : 생성자 함수
const gaji = new User("KOREA", "Busan")
const local = new User("KOREA", "Seoul")

(참고 : https://www.youtube.com/watch?v=wUgmzvExL_E)

1. prototype

객체에 직접 포함되지는 않지만 원할 때 찾아서 사용 가능한거

function User (country, city) {
  this.country = country;
  this.city = city;
}  

User.prototype.getAddress = function () {
  return `${this.country} ${this.city}`
}

const gaji = new User("KOREA", "Busan") 
gaji            // {country: 'KOREA', city: 'Busan'}
gaji.firstName  // KOREA Busan

용도

const arr = new Array(1,2,3)
arr.sort()      // Array.prototype.sort()
arr.length()    // Array.prototype.length()

자주 사용하는 함수 등을 prototype에 저장할 수 있다

※ prototype 함수 작성 시 화살표함수 쓰면 안됨

2. ES6 클래스 문법

class User {
  constructor (country, city) {
    this.country = country;
    this.city = city;
  }
 
  getAddress = function () {
    return `${this.country} ${this.city}`
  }
}

객체 안에 직접 만들면 이렇게됨

class User {
  constructor (country, city) {
    this.country = country;
    this.city = city;
    this.Address = `${this.country} ${this.city}`
  }
}

const gaji = new User("KOREA", "Busan") 

// 이사 갔는데 주소가 안바뀜
gaji.city = "Seoul"
gaji  // {city : "Seoul", Address: "KOREA Busan"}

3. Getter, Setter

  • get : 함수 호출 안하고 값을 얻을 때 사용, 메서드를 속성처럼 사용 가능
  • set : 값이 변경될 때마다 함수를 실행시켜서 객체를 업데이트
  1. getter을 추가해서 함수 호출 없이 주소를 얻기
class User {
  constructor (country, city) {
    this.country = country;
    this.city = city;
  }
 
  get address () {
    return `${this.country} ${this.city}`
  }

}
const gaji = new User("KOREA", "Busan")

gaji.address // KOREA Busan
  1. 문제점 : 값을 재할당해도 객체가 바뀌지않음
gaji.address = "USA LA" // 이민감
gaji         // {country: 'KOREA', city: 'Busan'}
gaji.address // KOREA Busan
  1. setter를 사용해서 재할당 될때마다 함수가 실행되게 함
class User {
  constructor (country, city) {
    this.country = country;
    this.city = city;
  }
 
  get address () {
    return `${this.country} ${this.city}`
  }
  
  // setter 추가 
  set address (value) {
    ;[this.country, this.city] = value.split(' ')
  }
}
const gaji = new User("KOREA", "Busan")

gaji.address = "USA LA" 
gaji // {country: 'USA', city: 'LA'}

4. 정적 메소드

클래스에는 프로토타입 메소드와 그냥 (정적) 메소드가 있음

프로토타입정적메소드
인스턴스로 호출클래스로 호출
this로 인스턴스의 프로퍼티를 참조 가능this로 인스턴스의 프로퍼티를 참조 가능
  1. 프로토타입 형식으로 메소드 생성
class User {
  constructor (country, city) {
    this.country = country;
    this.city = city;
  }
  
  // 프로토타입
  getAddress () {
    return `${this.country} ${this.city}`
  }
}
const gaji = new User("KOREA", "Busan")

gaji.getAddress() // 인스턴스 호출: KOREA Busan
User.getAddress() // 클래스 호출 : 에러발생
  1. 정적 메소드 생성
class User {
  constructor (country, city) {
    this.country = country;
    this.city = city;
  }
 
  // 정적 메소드
  static isUser(name) {
    if (name.country && name.city) {
      return true
    }
    return false
  }
}
const gaji = new User("KOREA", "Busan")

User.isUser(gaji)  // true
User.isUser(local) // false
gaji.isUser()      // 인스턴스 호출: 에러발생

5. 상속과 instanceof

extends : 클래스 상속받기

class B extends A {
  // 내용
}

super() : 부모 클래스의 constructor 함수 상속받기

class A {
  constructor(value = 1){
    this.value = value // value 기본값 1
  }
}

class B extends A {
  constructor(value){
    super(value)    // A의 constructor 상속 받기
  }
}

const a = new A()
const b = new B(2)
a  // {value: 1} 
b  // {value: 2}

A instanceof B : A는 B의 인스턴스인가

a instanceof A     // true
b instanceof A     // true  (부모클래스도 ok)
a instanceof B     // false

B의 진짜 출처 확인하기

b.constructor === A   // false
b.constructor === B   // true : b는 B에서 생성된 인스턴스

0개의 댓글