객체와 자료 구조
게터와 세터 사용
객체 프로퍼티 접근 시 게터/세터 사용이 직접 접근에 비해 나은 점:
- 객체 프로퍼티 조회 외 추가 작업이 필요할 때, 코드베이스 전반의 접근자를 수정할 필요가 없음
- 값 설정 시(set) 유효성 검증 구현 용이성
- 내부 데이터 표현 방식 캡슐화 가능
- 프로퍼티 접근/설정 시 로깅 및 오류 처리 추가 간편화
- 객체 프로퍼티 지연 로딩 가능 (예: 서버에서 데이터를 가져오는 경우)
나쁜 예시:
javascript
function makeBankAccount() {
// ...
return {
balance: 0
// ...
};
}
const account = makeBankAccount();
account.balance = 100;좋은 예시:
javascript
function makeBankAccount() {
// this one is private
let balance = 0;
// a "getter", made public via the returned object below
function getBalance() {
return balance;
}
// a "setter", made public via the returned object below
function setBalance(amount) {
// ... validate before updating the balance
balance = amount;
}
return {
// ...
getBalance,
setBalance
};
}
const account = makeBankAccount();
account.setBalance(100);객체 비공개 멤버 구현
ES5 및 이전 버전에서는 클로저를 통해 구현 가능
나쁜 예시:
javascript
const Employee = function(name) {
this.name = name;
};
Employee.prototype.getName = function getName() {
return this.name;
};
const employee = new Employee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined좋은 예시:
javascript
function makeEmployee(name) {
return {
getName() {
return name;
}
};
}
const employee = makeEmployee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe