기술 면접 정리/자바스크립트

4장 콜백함수 정리

테오구 2022. 5. 4. 17:57
728x90

콜백 함수는 다른 코드에 인자로 넘겨줌으로써 그 제어권도 함께 위임하는 함수

 

map 메서드

 

Array.prototype.map(callback[,thisArg])
callback: function(currentValue, index, array)

첫번째로 인자로 callback 함수를 받고, 생략 가능한 두 번째 인자로 콜백함수 내부에서 this로 인식할 대상을 특정할 수 있습니다.

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

콜백함수 내부의 this에 다른 값 바인딩하기 

const obj1 = {
	name: 'obj1',
    func:function(){
    	console.log(this.name)
    }
}
setTimeout(obj1.func.bind(obj1),1000)

const obj2 = {name: 'obj2'}
setTimeout(obj1.func.bind(obj1),1500)

콜백 지옥

콜백 함수를 익명 함수로 전달하는 과정이 반복되어 코드의 들여쓰기가 많이지는 현상

이를해결하기 위해서

promise + Async/await를 사용합니다.

const coffee = function(name){
	return new Promise(function(resolve){
    	setTimeout(function(){
        	resolve(name)
        }, 500)
    })
}
const maker = async function(){
	let coffeeList = ''
    const addCoffee = async function(name){
    	coffeeList += (coffeeList ? ',':'') + await addCoffee(name)
    }
    await addCoffee('아메리카노')
    console.log(coffeeList)
    await addCoffee('카페라떼')
    console.log(coffeeList)
    await addCoffee('달고나라떼')
    console.log(coffeeList)
    await addCoffee('카페모카')
    console.log(coffeeList)
}
maker()
728x90

'기술 면접 정리 > 자바스크립트' 카테고리의 다른 글

프로토타입  (0) 2022.06.01
구조분해 할당  (0) 2022.04.21
이벤트 루프  (0) 2022.04.15
자바스크립트 엔진  (0) 2022.04.15
preventDefault(); 와 stopPropagation(); 차이  (0) 2022.04.12