TIL - getter & setter

Minsoo·2021년 7월 23일
0

TIL

목록 보기
5/8
post-thumbnail

☄️ Getter

  • Getters can perform an action on the data when getting a property.

  • Getters can return different values using conditionals.

  • In a getter, we can access the properties of the calling object using this

  • The functionality of our code is easier for other developers to understand.

  • Literally, When you get something, it will return something.

  • When using getter (and setter) methods is that properties cannot share the same name as the getter/setter function. Otherwise, It will cause the call stack error.
    👉 그래서 게터와 세터안에 쓰여지는 변수이름을 보통 앞에'_'이용해 변수이름 다르게 함.

const person = {
  _firstName: 'John',
  _lastName: 'Doe',
  get fullName() {
    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'

☄️ Setter

  • checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used.
const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors(){
    if(typeof this._numOfSensors === 'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently down.'
    }
  },
  set numOfSensors(num) {
if(typeof num === "number" && num >= 0) {
  return this._numOfSensors = num
} else {
console.log( 'Pass in a number that is greater than or equal to 0')
}
  }
}; 
robot.numOfSensors = 100;
console.log(robot.numOfSensors)

☄️ in a nutshell

getter

값 리턴.
게터를 정의하는 순간 위의 프로퍼티 데이터를 받아오는 것이 아니라 게터를 호출하게된다.

setter

값 설정.
새로운 받은 밸류를 사용하여 값 설정. 세터를 정의하는 순간 메모리 값을 업데이트 하는 것이 아니라 세터를 호출하는 것.

사용자가 설정할 수 없는 값을 쓸 수 없도록 세터를 이용해 설정.

참고자료
codecademy https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/setters

드림코딩 https://www.youtube.com/watch?v=_DLhUBWsRtw
9:30 ~

profile
Hello all 👋🏻 📍London

0개의 댓글