get
키워드는 함수 앞에 위치한다.
일반적으로 getter(setter) 메서드는 괄호()
없이 호출되어, 문법적으로는 속성에 접근하는 것처럼 보인다.
getter 메서드 사용 시 장점
- getter는 속성을 가진 데이터에 대해 작업을 수행할 수 있다.
- getter는 조건을 이용하여 다양한 값을 반환할 수 있다.
- getter에서 'this'를 이용하여 호출객체의 속성에 접근하는게 가능하다.
- 다른 개발자가 함수 코드를 더 이해하기 쉽게 한다.
유념할 점은 getter(setter) 메서드를 이용할 때 속성(property)은 getter(setter) 함수 이름은 동일해선 안된다. (단, get 과 set 함수 이름은 같아도 된다.)
메서드를 호출할 때 무한대의 호출순서 에러(infinite call stack error)가 날 수 있다.
이럴경우 속성 앞에 _
를 붙여 해결할 수 있다.
https://discuss.codecademy.com/t/why-use-a-getter-and-not-a-method/435491
메서드가 아닌 getter를 사용하는 이유.....? 이해하기가 어렵다.
const person = {
_firstName: 'John',
_lastName: 'Doe',
get fullName() { // 함수이름 앞에 get을 붙임.
if (this._firstName && this._lastName){
return `${this._firstName} ${this._lastName}`;
} else {
return 'Missing a first name or a last name.';
}
}
}
// To call the getter method:
person.fullName; // 'John Doe'
- 입력 확인
- 속성 동작 수행
- 객체 사용 방법에 대한 명확한 의도 표시 등
const person = {
_age: 37,
set age(newAge){
if (typeof newAge === 'number'){
this._age = newAge;
} else {
console.log('You must assign a number to age');
}
}
};
person.age = 40; // setter 함수를 호출하여 변수(newAge)에 40을 할당하였다.
console.log(person._age); // Logs: 40, 객체 안의 속성 값이 변경되었다.
person.age = '40'; // Logs: You must assign a number to age
person._age = 'forty-five' //객체 속성에 접근하여 직접 값 수정.
console.log(person._age); // Prints forty-five