devSoyoung / STUDY

✏️ 공부한 내용 정리, 주제에 따라 분류
4 stars 1 forks source link

접근자 프로퍼티(Accesor Property): getter, setter #29

Open devSoyoung opened 4 years ago

devSoyoung commented 4 years ago

접근자 프로퍼티 정의하기

  1. 객체 생성 시 정의하는 방법
  2. Object.defineProperty()로 정의하는 방법
// 객체 생성 시 정의
const obj = {
  state: 'loading',
  get currentState() {
    return this.state;
  },
  set changeState(state) {
    this.state = state;
  },
};
// Object.defineProperty()로 정의
const obj = {};
Object.defineProperty(obj, "currentState", { get: function() { return this.state; } });
Object.defineProperty(obj, "newState", { set: function(state) { this.state = state; } });

접근자 프로퍼티 삭제하기

delete obj.currentState;

getter의 특징: smart, self-overwriting, lazy

Object.assign()으로 복사될 때

const supplier = {
  state: 'loading',
  get currentState() {
    return this.state;
  },
  set changeState(state) {
    this.state = state;
  },
};

const receiver = Object.assign({}, supplier);

console.log(receiver.currentState);          // 'loading'
console.log(receiver.changeState);           // undefined

supplier.changeState = 'done';
console.log(supplier.currentState);          // 'done'
console.log(receiver.currentState);          // 'loading'