-
getter와 setter, get과 set 키워드 [작성중]FRONTEND/Javascript 2022. 7. 25. 00:32
참고한 자료
https://ko.javascript.info/property-accessors#ref-2602
https://www.youtube.com/watch?v=_DLhUBWsRtw
https://ko.javascript.info/property-accessors
get과 set 키워드
getter method (획득자)는 get으로 나타내고, 값을 리턴해주는 역할을 합니다.
setter method(설정자)는 set으로 나타내고, 값을 설정해주는 역할을 합니다. 이 때 set은 value가 들어와야 합니다.
let obj = { get propName() { // getter, obj.propName을 실행할 때 실행되는 코드 }, set propName(value) { // setter, obj.propName = value를 실행할 때 실행되는 코드 } };
get은 obj.propName을 사용해 property를 읽으려 할 때 실행되고,
set은 obj.propName = value으로 property에 value를 할당하려 할 때 실행됩니다.
let user = { name: "John", surname: "Smith", get fullName() { return `${this.name} ${this.surname}`; } }; alert(user.fullName); // John Smith
이 경우 user.fullName = ~~~~ 를 사용해 값을 할당할 수 없습니다.
fullName은 getter 메서드만 가지고 있기 때문에 값을 리턴할 수는 있지만
값 설정도 할 수 있도록 하려면 setter 메서드까지 있어야 하는 것입니다.
let user = { name: "John", surname: "Smith", get fullName() { return `${this.name} ${this.surname}`; } }; user.fullName = "test"; // (프로퍼티에 getter 메서드만 있어서 에러가 발생합니다.)
값이 할당이 안되는 것을 콘솔창으로 확인 아래와같이 getter와 setter 메서드를 구현하면
객체에는 fullName이라는 읽고 쓸 순 있지만 실제로는 존재하지 않는 가상의 property가 생깁니다.
let user = { name: "John", surname: "Smith", get fullName() { return `${this.name} ${this.surname}`; }, set fullName(value) { [this.name, this.surname] = value.split(" "); } }; // 주어진 값을 사용해 set fullName이 실행됩니다. user.fullName = "Alice Cooper"; alert(user.name); // Alice alert(user.surname); // Cooper
set까지 설정한 뒤에는 값 설정도 가능함을 확인. another example
class User { constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } get age() { return this._age; } set age(value){ if (value < 0){ throw Error ('age can not be negative'); } this._age = value < 0 ? 0 : value ; } } const user1 = new User('kim','dung',4); console.log(user1.age);
get과 set을 정의해주면
어떤 메서드에서 밸류 값에 들어오면 안되는 값이 들어올경우에 getter에서
'FRONTEND > Javascript' 카테고리의 다른 글
문자열 대체하기 (replace, replaceAll) (0) 2022.08.01 자꾸 헷갈려서 빡쳐서 쓰는 글 (splice, split, slice) (0) 2022.07.28 프로토타입 체인 (extends, super) (0) 2022.07.24 프로토타입과 클래스 (prototype,__proto__) (0) 2022.07.24 객체 지향 프로그래밍 (OOP) 주요 개념 4가지 (캡슐화, 추상화, 상속, 다형성) (0) 2022.07.24