💻 JavaScript/기초 문법

JS 문법 종합: 일급 객체로서의 함수

seheej 2024. 7. 25. 17:01

일급 객체란

: 다른 객체들과 일반적으로 적용 가능한 연산을 모두 지원하는 객체를 가르킨다 (=다른 객체와 일반적으로 같다)

 

1. 변수에 함수를 할당

  • 함수가 마치 값으로 취급된다.
  • 함수가 나중에 사용될 있도록 조치가 되었다.
const sayHello = function () {
    console.log("Hello!");
}

 

2. 함수를 인자로 다른 함수에 전달

  • 콜백 함수: 매개변수로서 쓰이는 함수
  • 고차 함수: 함수를 인자로 받거나 return하는 함수
  • 콜백함수(함수로 인자로 받음) 고차함수의 종류
function callFunction(func) {
    //매개변수로 받은 변수 func가 사실, 함수다.
    func()
}
function callFunction(func) {
    //매개변수로 받은 변수 func가 사실 함수다.
    func()
}

const sayHello = function () {
    console.log("Hello!");
}

callFunction(sayHello);
const sayHello = function () {
    console.log("Hello!");
}

//************************** 아래의 매커니즘으로 코드가 들어감 ************************** //

callFunction(sayHello); //callFunction을 실행할 때, sayHello 함수를 매개변수로 던질 수 있음

callFunction(function () {  // callFunction(func)에서 매개변수 func로 sayHello라고 저장된 함수가 func로 전달됨
    console.log("Hello!");
});

function callFunction(function () {
    console.log("Hello!");
}) {
    //매개변수로 받은 변수 func가 사실 함수다.
    func()
}

 

3. 함수를 반환

function createAdder(num) {
    return function (x) {
        return x + num;
    }
}
const addFive = createAdder(5); 
console.log(addFive(10));	// 15
function createAdder(num) {
    return function (x) {
        return x + num;
    }
}

const addFive = createAdder(5); // createAdder를 실행한 결과
// 다음과 같이 대체 됨
const addFive = function (x) {
    return x + 5;
}

console.log(addFive(10)); // addFive를 실행한 결과
// 다음과 같이 대체 됨
console.log(function (10) {
    return 10 + 5;
});	// 고로 결과값 15 출력​

 

4. 객체의 프로퍼티로 함수를 할당

: 객체의 메소드로 함수를 호출할 수 있다.

const person = {
    name: 'John',
    age: 31,
    isMarried: true,
    sayHello: function () {
        console.log("Hello, my name is " + this.name);
    }
}

person.sayHello();	// "Hello, my name is John" 출력
// 템플릿 리터럴로도 가능
const person = {
    name: 'John',
    age: 31,
    isMarried: true,
    sayHello: function () {
        console.log(`Hello, my name is ${this.name}`);
    }
}

person.sayHello();	// "Hello, my name is John" 출력
// 화살표 함수를 사용한 방법
/**
 * 화살표 함수 사용 시 this를 바인딩하지 않는다.
 */
const person = {
    name: 'John',
    age: 31,
    isMarried: true,
    sayHello: () => {
        console.log(`Hello, my name is ${this.name}`)   // 출력 시 this.name이 undefined로 출력됨
    }
}

 

5. 배열의 요소로 함수를 할당

const myArr = [
    function (a, b) {
        return a + b
    }, function (a, b) {
        return a - b
    }
]

// function은 ()로 실행하는데 function에 접근하기 위해 배열의 요소를 접근하는 방법 그대로 접근

// 더하기
console.log(myArr[0](1, 3));    // 4

// 빼기
console.log(myArr[1](10, 7));   // 3

 

 

 

function multiplyBy(num) {
    return function (x) {
        return x * num;
    }
}

function add(x, y) {
    return x + y;
}

const multiplyByTwo = multiplyBy(2);
/**
 * 1. multiplyBy의 리턴값이 오른쪽으로 옴
 * 2. multiplyBy(2)의 2가 multiplyBy(num)의 num으로 대체
 */
// const multiplyByTwo = function (x) {
//     return x * 2;
// };

console.log(multiplyByTwo(10)); // 20

// const multiplyByThree = multiplyBy(3);
/**
 * 1. multiplyBy의 리턴값이 오른쪽으로 옴
 * 2. multiplyBy(3)의 3가 multiplyBy(num)의 num으로 대체
 */
 
const multiplyByThree = function (x) {
    return x * 3;
};

console.log(multiplyByThree(10));   // 30

const result = add(multiplyByTwo(5), multiplyByThree(10));  // (2 * 5) + (3 * 10)
console.log(`Final: ${result}`);    // 40