Class활용

youngseo·2022년 5월 4일
0

새로배운 내용

목록 보기
27/42

Class

Class 실활용 및 staic메소드와 prototype메소드 비교

  <div class="font1">Color</div>
  <div class="font1">Blue?</div>

  <div class="font2">Heropy</div>
  <button class="btn1">OK!</button>
  <button class="btn2">OK?!</button>
  <button class="btn3">Getter?!</button>
class Fonty {
  constructor(selector, customOptions) {
    const defaulOptions = {
      fontSize: '16px',
      fontWeight: '700',
      color: 'black',
    }
    //옵션병합
    this.options = {
      ...defaulOptions,
      ...customOptions
    }
    //요소 검색
    this.els = document.querySelectorAll(selector)
    this.setStyle(this.options)
  }
  //사용자가 입력한 style을 받음 ex {color: 'red', fontSize: '20px'}
  setStyle(style) {
    this.els.forEach(el => {
      //이렇게 입력하는 경우 덮어써져 기존의 내용이 사라짐
      // el.style = style
      Object.assign(el.style, style) // 따라서 이렇게 병합해야함
    })
  }
  //정적메소드
  static setRed(instance) {
    instance.setStyle({
      color: 'red'
    })
  }
  //정적메스드 예시2 
  static getFamilies() {
    return ['serif', 'sans-serif', 'monospace', 'cursive']
  }

  // Getter
  get fontSize() {
    console.log('in Getter', this.options.fontSize)
    return this.options.fontSize
  }
  // Setter
  set fontSize(value) {
    console.log('in Setter', value)
    // this.options.fontSize = value
  }
}


//사용예시 (내부)
new Fonty('.font1', {
  fontSize: '30px',
  fontWeight: '400',
  color: 'red'
})

//setStyle 외부에서 사용예시
const fonty = new Fonty('.font2', {
  fontSize: '40px',
  fontWeight: '700',
  color: 'blue'
})

document.querySelector('.btn1').addEventListener('click', () => {
  fonty.setStyle({
    color: 'black'
  })
})

//정적메소드 사용 예시
document.querySelector('.btn2').addEventListener('click', () => {
  Fonty.setRed(fonty)
})

// *static 메소드 : class에 붙어 실행
// *prototype메소드: instace에 붙어 실행

//매번 똑같은 결과를 반환하기에 이 statit 메소드가 인스턴스에서 실행됟 필요가 없음
console.log(Fonty.getFamilies) // 따라서 이런식으로 바로 호출하는 방식으로 사용할 수 있다.

//⭐Getter(값을 얻어냄): 메소드가 아니라 단순 속성이다 
//- porotype메소드 앞에 get을 붙임
// 값을 얻어내는 것에서 그치지 않고 아래와 같이 어떤 로직을 추가할 수 있다.
// 함수이지만 리턴키워드로 반환하는 데이터를 마치 속성처럼 쓰게 함
// 즉 get이 붙어있는 메소드는 마치 속성처럼 사용을 하면 됨 //getter "fonty.fontSize()" 로 쓰는 것이 아니라 ()을 지워야함

//⭐Setter
//getter에다가 값을 지정하면 set함수가 실행됨

document.querySelector('.btn3').addEventListener('click', () => {
  //getter "fonty.fontSize()" 로 쓰는 것이 아니라 ()을 지워야함
  console.log(fonty.fontSize)
  // 실제 속성처럼 값을 지정하면 set함수가 동작함
  fonty.fontSize = '99px'
})

getter, setter

class User {
  constructor(first, last) {
    this.first = first
    this.last = last
  }
  // 풀네임을 얻는데 굳이 함수로 쓸 필요가 있을까 싶어, get으로 바꿈
  // fullName() {
  //   return this.first + ' ' + this.last
  // }
  get fullName() {
   // return this.first + ' ' + this.last
    //보관법을 사용하는 경우
    return `${this.first} ${this.last}`

  }

  set fullName(value) {
    const res = value.split(' ')
    this.first = res[0]
    this.last = res[1]
    
   //구조분해할당으로 한다면
    const [first, last] = value.split(' ')
    this.first = first
    this.last = last
    
  }

}

const heropy = new User('Heropy', 'Park')
// console.log(heropy.fullName())
console.log(heropy.fullName)

heropy.fullName = 'Leon Miller'
console.log(heropy.fullName)

0개의 댓글