Open devSoyoung opened 4 years ago
getter
setter
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;
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'
getter
: 객체의 프로퍼티를 그 프로퍼티를 가져올 때 호출되는 함수setter
: 어떤 객체의 속성을 설정하려고 할 때 호출되는 함수접근자 프로퍼티 정의하기
Object.defineProperty()
로 정의하는 방법접근자 프로퍼티 삭제하기
getter의 특징: smart, self-overwriting, lazy
Object.assign()으로 복사될 때
getter
: 접근자 프로퍼티가 아니라 실행한 결과를 일반 프로퍼티로 가짐setter
: 일반 프로퍼티로 복사되고, 값은 undefined가 됨