ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS] Getter와 Setter
    Algorithm & Data Structure 2022. 1. 25. 22:34
    SMALL

    자바스크립트는 객체 기반의 프로그래밍 언어이다.

    객체는 0개 이상의 프로퍼티(property)로 구성된 집합이며, 프로퍼티는 key와 value로 구성된다.

    let person = {
    	name: 'Dahee',
        // name~dahee까지 프로퍼티, name은 프로퍼티 키, dahee는 프로퍼티 밸류
    };

    프로퍼티 value 가 함수일 경우에 메서드라 부른다.

    개념 이해하는데 한참 걸린 getter와 setter...

    const person = {
    	firstName: 'Dahee',
        lastName: 'Jo',
        get fullName() {
        	return `${person.firstName} ${person.lastName}`
        },
        set fullName(value) {
        	const parts = value.split(' ');
            this.firstName = parts[0];
            this.lastName = parts[1];
        }
     };
     
     person.fullName = 'John Smith';
     
     console.log(person);
     
     // {fisrtName: "John", lastName: "Smith"}

    위 예시처럼 내가 예시를 만들어 봤을 때도 살짝 아리까리했지만.. free code camp에서 자바스크립트 공부 중 다시 게터 세터를 마주하게 되어 다시 공부를 해보니 이젠 90% 이해가 된 것 같다.(활용까지 할 수 있을 때 100%로 보기로 함.)

    https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object

     

    https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object

     

    www.freecodecamp.org

     

    Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
    Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.
    class Book {
      constructor(author) {
        this._author = author;
      }
      // getter
      get writer() {
        return this._author;
      }
      // setter
      set writer(updatedAuthor) {
        this._author = updatedAuthor;
      }
    }
    const novel = new Book('anonymous');
    console.log(novel.writer); //anonymous
    novel.writer = 'newAuthor';
    console.log(novel.writer); //NewAuthor

    *보통 private variable을 쓸 때 앞에 _를 붙이는 게 컨벤션이라고 한다. 

     

    아래는 free code camp에서 나온 적용 문제이다.

    getter를 통해 화씨를 섭씨온도로 변환하여 리턴하고, setter를 통해 아래 새로 입력받은 섭씨온도를 화씨로 바꾸어 값을 set한다.

    class Thermostat {
      constructor(Fahrenheit){
        this._Fahrenheit = Fahrenheit;
      }
      get temperature(){
        return 5/9 * (this._Fahrenheit-32);
      }
      set temperature(celsius){
        this._Fahrenheit = celsius*9.0/5+32;
      }
    }
    // Only change code above this line
    
    const thermos = new Thermostat(76); // Setting in Fahrenheit scale
    let temp = thermos.temperature; // 24.44 in Celsius
    thermos.temperature = 26;
    temp = thermos.temperature; // 26 in Celsius
    반응형

    댓글

Designed by Tistory.