aotoyae

[JS] First Class Object 일급 객체 함수, 고차함수 ,함수 활용 본문

JavaScript

[JS] First Class Object 일급 객체 함수, 고차함수 ,함수 활용

aotoyae 2024. 1. 2. 17:48

 

 

일급 객체로서의 함수를 활용해 보자~

 

💡 변수에 함수 할당

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

 

💡 객체의 프로퍼티로 할당

const person = {
  name: "aoto",
  age: 20,
  isMarried: false,
  sayHello: function () {
    console.log(`Hello, My name is ${this.name}`);
  },
};

person.sayHello(); // Hellow, My name is aoto

 

💡 배열의 프로퍼티로 할당

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

console.log(myArr[0](2, 3)); // 5
console.log(myArr[1](3, 10)); // -7

 

💡 함수를 인자로 다른 함수에 전달 가능

콜백함수 : 매개변수로 쓰이는 함수

고차함수 : 함수를 인자로 받거나 return 하는 함수

function callFunction(func) {
  // 매개변수 = 함수
  func();
}

callFunction(sayHello);

// 함수 반환 가능 (고차함수)
function createAdder(num) {
  return function (x) {
    return x + num;
  };
}

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

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

const multiplyByTwo = multiplyBy(2);
// const multiplyByTwo = function (x) {
//   return x * 2;
// };
console.log(multiplyByTwo(10)); // 20

const multiplyByThree = multiplyBy(3);
// const multiplyByThree = function (x) {
//   return x * 3;
// };
console.log(multiplyByThree(20)); // 60

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

const addEach = add(multiplyByTwo(10), multiplyByThree(20));
console.log(addEach); // 80