-
[JS] Getter와 SetterAlgorithm & Data Structure 2022. 1. 25. 22:34SMALL
자바스크립트는 객체 기반의 프로그래밍 언어이다.
객체는 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
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
반응형'Algorithm & Data Structure' 카테고리의 다른 글
[JS]어쩌다 까먹는 자바스크립트 배열 메소드/함수 총정리 (0) 2022.03.13 [JS/Node.js] readline을 통한 입출력 (0) 2022.03.12 [JS] 재귀 함수(Recursive Function) (0) 2022.01.31