CSS&JS/👀Study and Copy

getter,setter

arancia_ 2022. 6. 3. 11:16

모던 자바스크립트 튜토리얼 : 프로퍼티 getter와 setter

 

프로퍼티 getter와 setter

 

ko.javascript.info

그냥 예제 따라하면서 공부한거 메모

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* 기본 */
    const test = {
        firstName : "Din",
        lastName : "Djarin",
 
        get fullName(){
            return `${this.firstName} ${this.lastName}`;
        },
 
        set fullName(value){
            [this.firstName, this.lastName] = value.split(' ');
        }
    };
 
    console.log(test.fullName); //Din Djarin
    test.fullName = "Din Skywalker";
    console.log(test.fullName); //Din Skywalker
    console.log(test.lastName); //Skywalker
 
    /* 외부에서 설정하는 방법도 있음 */
    const test2 = {
        firstName : "Ahsoka",
        lastName : "Tano"
    }
 
    Object.defineProperty(test2, 'fullName',{
        get(){ return `${this.firstName} ${this.lastName}`; },
 
        set(value){ [this.firstName, this.lastName] = value.split(' '); }
    });
 
    console.log(test2.fullName); //Ahsoka Tano
    test2.fullName = 'Ahsoka Kryze';
    console.log(test2.fullName); //Ahsoka Kryze 
    console.log(test2.lastName); //Kryze 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* getter와 setter 똑똑하게 활용하기 */
    const user = {
        get name(){
            return this._name;
        },
 
        set name(value){
            if(value.length<4){console.log('이름이 너무 짧음'); return;}
            this._name = value;
            console.log('이름은 : ',this._name);
        },
    };
 
    user.name = "Hello";  //이름은 :  Hello
    user.name="a"//이름이 너무 짧음
 
    console.log(user.name); //Hello
    console.log(user); //{_name: 'Hello'} //실제로 name은 존재하지 않음.
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* 호환성을 위해 사용하기 */
    function User_old(name,age){
        this.name = name;
        this.age = age;
    }
 
    let pedro = new User_old("Pedro Pascal",40); //1975-04-02
    console.log('매년 업데이트 해야겠네',pedro.age); //40
 
    /* 그 때 클라이언트가 나타나 this.age 대신 birthday로 바꾸라고 했다 */
    /* DB에는 이미 수백만건이 저장되어있다고 할 때 .. 어케함? */
    /* age는 딱히 지울 필요 없으니 다음과 같이 수정하자 */
 
    function User(name,birthday){
        this.name = name;
        this.birthday = birthday;
 
        //age는 현재 날짜와 생일을 기준으로 계산한다.
        Object.defineProperty(this,"age",{
            get(){
                const todayYear = new Date().getFullYear();
                return todayYear - this.birthday.getFullYear();
            }
        });
    }//User
 
    pedro = new User("Pedro"new Date(1975,04,02));
    console.log(pedro.age); //47
cs