클로저 참조 캡쳐

임혁진·2023년 10월 20일
0

로빌

목록 보기
6/15

클로저가 참조를 캡쳐한다는 관점에서 직접 문제를 만들어봤다.

// 2가지 방식의 클로저 
class myClass {
    constructor() {
        this.addConstant = 1;
    }
    changeConstant(value) {
        this.addConstant = value;
    }
    
    getMyAdd1() {
        const myAddConstant = this.addConstant;
        return (a) => a + myAddConstant;
    }
    
    getMyAdd2() {
        return (a) => a + this.addConstant;
    }
}

const myObj = new myClass();
const addFunc1 = myObj.getMyAdd1();
const addFunc2 = myObj.getMyAdd2(); 
myObj.changeConstant(5);

console.log(addFunc1(5)); // 6 (1 + 5)
console.log(addFunc2(5)); // 10 (5 + 5) 
// 클로저는 참조를 캡쳐한다.
// 1. myObj.getMyAdd2()가 호출될 때 this는 myObj와 바인딩된다.
// 2. getMyAdd2()의 리턴함수는 this의 참조를 캡쳐한다.
// 3. myObj.addConstant가 변하면 getMyAdd2() 내부의 함수의 참조값이 변화되므로 그에 따라 값도 변한다.
profile
TIL과 알고리즘

0개의 댓글