JavaScript/4주차

4. 콜백 함수 - this 바인딩

tnals634 2023. 5. 25. 11:39

this

- 제어권을 넘겨받을 코드에서 콜백 함수에 별도로 this가 될 대상을 지정한 경우에는 그 대상을 참조

 

- call, apply

 

 

//setTimeout 은 내부에서 콜백 함수를 호출할 때,
//call 메서드의 첫번째 인자에 전역객체를 넘긴다.
//따라서 콜백 함수 내부에서의 this가 전역객체를 가리킨다.
setTimeout(function () { console.log(this);},300); //global

//forEach도 마찬가지로 콜백 뒷 부분에 this를 명시해주지 않으면
//전역객체를 넘긴다. 만약 명시한다면 해당 객체를 넘긴다.
[1,2,3,4].forEach(function(x) {
    console.log(this); //global
});

//만약 아래와같이 {x:1}처럼 명시적으로 넣어주면 해당 객체를 넘긴다.
// [1,2,3,4].forEach(function(x) {
//     console.log(this); //{x:1}을 4번 출력
// },{x:1});

//addEventListener은 내부에서 콜백 함수를 호출할 때,
//call 메서드의 첫번째 인자에 AEL 메서드의 this를 
//그대로 넘겨주도록 정의돼 있다.(상속)
document.body.innerHTML += '<button id="a">click</button>';
document.body.querySelector('#a').addEventListener('click',function(e){
    console.log(this,e);
});


//addEventListener을 이해하기 위해
//map함수를 직접 구현해보자.
Array.prototype.map123 = function(callback, thisArg) {
    //함수에서 return할 결과 배열
    var mappedArr = {};

    for(var i = 0; i<this.length; i++) {
        var mappedValue = callback.call(thisArg || global, this[i]);
        mappedArr[i] = mappedValue;
    }

    return mappedArr;
};
var newArr = [1,2,3].map123(function(number){
    return number * 2;
});

console.log(newArr); //{ '0': 2, '1': 4, '2': 6 }