Notice
Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

HYEWON JUNG의 개발일지

콜백함수 (제어권, this binding) 본문

JavaScript

콜백함수 (제어권, this binding)

혜won 2023. 10. 30. 20:59

1. 호출 시점에  대한 제어권

 let count = 0; 
 let timer = SetInterval(function(){
 	console.log(count);
    if(++count>4)ClearInterval(timer);
 },300);
 
 //SetInterval이 함수 실행 제어권을 가지고 있다. 
 //만약 제어권을 우리가 가지고 있다면 함수는 1번 돌고 멈춘다. 
 let count = 0; 
 let Func = function(){
 	console.log(count);
    if(++count>4)ClearInterval(timer);
 }
 
 let timer = SetInterval(Func,300);
 
 //이렇게 SetInterval의 매개변수를 따로 선언함. 위와 같은 식
 // 만약 호출을 Func(); 로만 했다면 함수는 1번 돈다.

2. 인자에 대한 제어권을 갖는다.  with map

map();은 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

let newArr = [10, 20, 30].map(function(currentValue,index){
	console.log(currentValue,index)
    
    return currentValue +5;//리턴값이 없으면 undefined*3
})
// 10 0/ 20 1 /30 2  currentValue가 요소를 하나하나 찍어줌 index가 index

console.log(newArr)
// [15, 25, 35]

//여기서 currentValue랑 index 순서를 바꿔 작성할 경우 역할이 반대가 되는데 
//간단하게 map()의 콜백함수의 인자는 자리별로 의미가 정해져 있고 
// currentValue랑index는 단지 변수명일 뿐!
//console.log(newArr)
// [5 , 6 , 7] 이렇게 찍힘

 

map에게 제어권이 있다. 

 

<콜백함수의 this>

콜백함수도 함수이기에 this는 전역객체를 참조한다. 하지만 제어권을 넘겨받을 코드에서 콜백함수에 별도록 this가 될 대상을 지정한 경우에는 그 대상을 참조한다.

 

이게 무슨 소리냐하면 

//Array.prototype.map이름  map이름으로 함수 처럼   호출 가능
//map은 항상 콜백함수를 받아서 callback, 
//두번째 인자로 this를 받는데 내부의 this랑 헷갈리지 않게 thisArg
Array.prototype.map12 = function(callback, thisArg){

//리턴할 객체를 미리 선언하기
    let mappedArr = [];
//여기서 this는 호출주체인 [1, 2, 3]을 참조
    for(let i = 0; i <this.length; i++){
//콜백한수 수행한 값 넣기 callback()
//this binding => call 즉시 실행함수 활용
//thisArg나 global이 들어왔으면 원래 들어왔어야 할 인자 this를 넣어줘
        let mappedVal = callback.call(thisArg||global, this[i]);
        mappedArr[i]= mappedVal;
    }
    return mappedArr;
};

let newArr= [1, 2, 3].map12(function(number){
    return number *2;
});

console.log(newArr);

콜백함수 내부에서 this를 명시적으로 binding하기에 가능한 것!

 

콜백함수 내부에서 this를 문맥에 맞게 참조할 수 있도록  하기

let obj1 ={
    name : "obj1",
    func : function(){
        let self = this;
        return function(){
            console.log(self.name);
        }
    },
}
let callback = obj1.func();
setTimeout(callback,1000)

//다른 효율적인 방법으로 쓰자.
let obj2 = {
    name : "obj2",
    func : obj1.func,
        //  function(){
        //     let self = this;
        //     return function(){
        //         console.log(self.name);
        //     }
        // },
}
let callback2 = obj2.func();
setTimeout(callback2,1500)

//call도 이용해보자

let obj3 = {name :"obj3"};
let callback3 = obj1.func.call(obj3);
setTimeout(callback3, 2000);

bind를 이용한다면

//bind도 이용해보자

let obj4= {
    name:"obj4",
    func: function(){
        console.log(this.name);
    },
}
//setTimeout(함수,시간)
//함수에 bind를 넣어서 this를 obj4로 할당
setTimeout(objs4.func.bind(obj4),1000)

//함수 자체를 bind해보자

let obj5 ={name : "obj5"};
setTimeout(obj4.func.bind(obj5),2000);
//얼마든지 원하는 요소를 this 바인딩 할 수 있다