callback 함수에서의 this 객체

yuna·2022년 11월 24일
0
post-thumbnail

우선 사내 소스 코드의 구조는 이랬다

const parent = {
    child: function() {
        this.child.apple = null,
        this.child.banana = null,
        this.child.orenge = null;

        this.child.prototype.init = function() {
            this.apple = "apple";
            
            console.log(this); // parent.child
            
            parent.fn1(this.propFn);
        }
        this.child.prototype.propFn = function(result) {
            console.log(this); //window
            console.log(result); // window
            
            this.banana = "banana";
        }
        
        this.child.prototype.init()
    },
    fn1: (pCallback) => {
        pCallback(this);
    }
}

console.log(`-------- 함수 실행 전 ---------
parent.child.prototype.apple: ${parent.child.prototype.apple}
parent.child.prototype.banana: ${parent.child.prototype.banana}`);

// 함수 실행
parent.child();

console.log(`-------- 함수 실행 후 ---------
- parent 객체
parent.child.prototype.apple: ${parent.child.prototype.apple}
parent.child.prototype.banana: ${parent.child.prototype.banana}

- window
banana: ${banana}
`);

console.log("apple: ", apple); // 여기서 undefined error 발생

collback 함수에서 호출하는 것은 익명함수로 치환되어 this가 window로 뜨게 됨

profile
나는야 개발자

0개의 댓글