본문 바로가기

Javascrpit

자바스크립트 - callback

이 포스팅은 생활코딩님 강의를 참고하여 작성합니다. 이 시리즈는 callback, promise, async & await 3편으로 구성할 예정입니다.

 

목차

1. first class citizen

2. callback 함수

 

first class citizen(1급 객체)


1급 객체란 변수로 할당할 수 있는 것을 말한다.

 

1은 변수로 할당할 수 있기 때문에 1급 객체이다.

const num = 1;

 

함수 또한 변수로 할당할 수 있기 때문에 1급 객체이다.

const say = (text) => {
    console.log(text);
}

 

 

자바를 배운 사람입장에서는 위 코드는 굉장히 낯설다. 자바에서는 함수가 1급 객체가 될 수 없기 때문이다.

 

조건문은 변수로 할당 할 수 없기 때문에 1급 객체가 될 수 없다.

const someVariable = if(something) {
	somelogic
}

 

 

1급 객체 되기 위한 또 다른 조건은 함수가 다른 함수의 리턴 값이 될 수 있다면 해당 프로그래밍 언어에서는 함수를 1급 객체라고 부른다.

function fn() {
    val = function() {
        return "hello";
    }
    return val;
}

 

또한 어떤 함수의 입력 값이 될 수 있다면 프로그래밍 언어에서는 그 것을 1급 객체라고 부른다.

val = function() {
    return "hello";
}

fn(val);

 

 

callback 함수


콜백 함수는 아래와 같이 이해하면 된다.

const val = function() {  
    return "hello";
}

function fn(arg) { // (2)
    arg();
}

fn(val); // (1) val 함수가 (2) fn 함수에 의해 호출됨 -> callback function

 

콜백 함수는 화살표 함수로 표현되는 경우가 많다. 자바 진영의 익명 객체와 람다식을 알고 있으면 쉽게 이해될 것입니다.

 

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);
console.log(result);

// 결과
// ['exuberant', 'destruction', 'present']

 

위 코드는 아래와 동일합니다. (물론 일반 함수와 화살표 함수에 기능적으로 완벽하게 동일한 것은 아님. 대표적으로 둘은 가리키는 this에서 차이가 존재)

 

1. 일반 함수를 사용할 경우

function getLongWord(e) {
    if (e.length > 6) {
        return true;
    } else {
        return false;
    }
}
const result = words.filter(getLongWord);

 

2. 익명 함수를 사용할 경우

const result = words.filter(function(element) {
    return element.length > 6;
})

 

3. 익명함수를 화살표 함수로 대체

const result = words.filter(word => word.length > 6);

 

 

4. 콜백 함수 직접 만들어보기

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
function myfilter(origin, callback) {
    let result = [];
    for(i = 0; i < origin.length; i++) {
        let current = origin[i];
        if (callback(current)) {
            result.push(current)
        }
    }
    return result;
}

newWords = myfilter(words, element => element.length > 6);

 

 

'Javascrpit' 카테고리의 다른 글

자바스크립트 - Promise(then, catch)  (0) 2023.06.18
Js - ES6 화살표함수  (0) 2023.06.13
변수 선언 방식 const, let, var  (0) 2023.05.31