다른 function, method에 arg를 넘겨줌으로써 그 제어권도 함께 위임한 함수이다.

callback: call back

제어권

호출 시점

var count = 0;
var func = function(){
	console.log(count);
	if (++count >4) clearInterval(timer); // 4번 하면 Interval 종료
}

var timer = setInterval(func,300); // 0.3초마다 자동 실행

var intervalID = scope.setInterval(func,delay[,param1, param2, ...]);

setInterval 구성요소 설명
scope Window 객체 또는 Worker의 인스턴스가 들어올 수 있다.
func 콜백 함수
delay ms 단위의 숫자이다. 매 delay마다 func이 실행된다.

어떤 값도 리턴하지 않지만 중간에 종료할 수 있게 하기 위해서(clearInterval) setInterval의 ID 값을 변수에 담는다.

인자

var newArr = [10,20,30].map(function (currentValue, index){
  console.log(currentValue,index);
  return currentValue + 5;
});
console.log(newArr);
// 10 0
// 20 1
// 30 2
// [15,25,35]

Array.prototype.map(callback[,thisArg])
// this의 기본값은 전역 객체이다.
callback: function (value, index, array)

callback으로 넘기는 인자들은 순서, 값이 정해져 있다. jquery처럼 index, value 순으로 주어도 value index 취급해버린다.

this

예외처리 관련은 제외하고 .map method를 직접 구현해서 this에 대해서 알아보자.

Array.prototype.map = function (callback, thisArg){
    var mappedArr = [];
    for (let index = 0; index < this.length; index++) {
      var mappedValue = callback.call(thisArg||window,this[index],i,this);
      mappedArr[index]=mappedValue;
    }
    return mappedArr;
}

call, apply method를 이용해서 thisArg를 지정해주는 코드 (thisArg || window) 를 생성하는 게 제일 핵심 원리이다.

setTimeout(function (){console.log(this);},300); //window

[1,2,3,4,5].forEach(function(x){
  console.log(this,x); //window, 1 * 5
})

document.body.addEventListener('click',function(e){
  console.log(this,e) // element
})

이제 위 코드를 살펴보자. setTimeout이나 forEach(this를 넘겨주지 않은 forEach)

의 경우는 window, 즉 내부에서 call, apply 같은 처리를 하지 않았기 때문에 this가

넘어가지 않는 것이고 addEventListener의 경우 내부 콜백 함수를 처리할 때 this를