Javascript

[JS]Closure에 대해

it('closure를 사용해 만든 property는 private하고 변경이 불가능합니다.', function() {
        function Person(firstname, lastname) {
            let fullName = firstname + ' ' + lastname;

            this.getFirstName = function() {
                return firstname;
            };
            this.getLastName = function() {
                return lastname;
            };
            this.getFullName = function() {
                return fullName;
            };
        }

        let aPerson = new Person('John', 'Smith');

        aPerson.firstname = 'Penny';
        aPerson.lastname = 'Andrews';
        aPerson.fullName = 'Penny Andrews';

        expect(aPerson.getFirstName()).toBe("John");
        expect(aPerson.getLastName()).toBe("Smith");
        expect(aPerson.getFullName()).toBe("John Smith");

        aPerson.getFullName = function() {
            return aPerson.lastname + ', ' + aPerson.firstname;
        };

        expect(aPerson.getFullName()).toBe("Andrews, Penny");
    });

  위의 코드를 보면 aPerson이 new Person의 값으로 할당되어진것을 볼수있는데 함수 Person의 객체 구성에는 또다른 함수 3개가 포함되어 있는 것을 볼수있다. 아래에서 호출하는 aPerson의 값을 보면 getFirstName() 실행된 값을 가져오는 것을 볼수있다. 이값은 "John"
이되는데 쉽게 생각해보면 이렇게 볼수있다

aPerson {getFirstName: ƒ, getLastName: ƒ, getFullName: ƒ}

그리고 아래에 보면 또다른 풀네임을 호출하는 함수가 하나있는데 그곳에서 보면 aPerson.lastname과 aPerson.firstname;을 요구하는 것을 볼수있다 이값은 쉽게생각하면 아래와 같이 볼수있다.

aPerson.firstname = 'Penny'; aPerson.lastname = 'Andrews';

한가지 생각해봐야할것은 아래와같이 선언되었다는 것이다 

aPerson {firstname: "Penny", lastname: "Andrews", getFirstName: ƒ, getLastName: ƒ, getFullName: ƒ, …}

이렇게 생각하면 접근할수있는 것과 없는것에대해 좀 명확히 판단할수 있는것 같다.

'Javascript' 카테고리의 다른 글

[JS] web기초 Flex Box  (0) 2020.08.14
[JS] if (Number(str[i])===true) 의 값  (0) 2020.08.09
[JS]Chain Scope 예시 2개  (0) 2020.08.04
[JS]Scope 변수의 변화 해설  (0) 2020.08.03
[JS]Object 기본개념  (0) 2020.07.19