[JS] Functions are first class

colki·2021년 5월 8일
0

Udemy_JavaScript: The Advanced JavaScript Concepts (2021) 강의를 바탕으로 메모한 내용입니다.

Functions are just objects

함수도 객체이기 때문에 프로퍼티들이 존재한다.


  • code() : invoke function

  • Name (option) : 함수 이름, 함수표현식이라면 anonymous가 올 것이다.

  • call()

  • apply()

  • bind()

    .
    .
    .

(단, call, apply, bind 등은 프로토체인으로 가져오는 속성이다.)

Functions are just objects in javascript

that means that we can pass them around like objects like things that contain data.

데이터를 가진 객체이기 때문에, 객체인 함수를 전달하고 받을 수도 있다.

단순히 코드로써 작업을 수행하는 것 이외에 데이터로 저장할 수 있는 것이다.

Functions are a first class citizen in JavaScript.

함수를 일급시민(일급함수)으로 만드는 세 가지 속성이 있다.

이것은 자바스크립트에서 함수를 HOF, 고차함수로 발전시키는 특징이기도 하다.

function () >> function(a, b) >> HOF

*HOF : Higher Order Function


① 객체의 변수와 속성에 함수를 할당할 수 있다.

functions can be assigned to variables and properties of objects.

함수를 변수에 담을 수도 있고, 값으로 쓸 수도 있다.

런타임에서 언제나 정의할 수 있고 들고 다닐 수 있고, 인자로 넘겨줄 수 있으며 원하는 시점에 평가할 수 있다. (bind, currry)

② 함수를 인자로써 함수의 매개변수로 전달할 수 있다.

We can also pass functions as arguments into a function.

즉 함수도 인자처럼 주고 받을 수 있다.

function foo(func) {
  func();
}

foo(function () {});

③ 함수를 다른 함수의 리턴 값으로 반환할 수 있다.

we can return functions as a values from other functions.

function foo() {
  return function () {};
}

higher order functions (HOF)


We can delay that until execution time and this gives us as you can see more flexibility.

We kept our code dry.

함수의 평가시점이 중요하지 않다

데이터가 당장 무엇인지 알 필요 없이 일단 전달하고 나~중에 호출할 때 정의하면 된다.

또한 실행 시간까지 함수 실행을 지연 할 수 있기 때문에 유연하고 드라이한 코드를 만들어준다.

Be careful

① initializing functions inside of loops.


루프 내에서 함수를 초기화 할 때 주의해야 한다.

// bad
// 함수가 5번 초기화 된다.
for (let i = 0; i < 5; i++) {
  function foo() { }
  foo();
}

⏬ move outside

// goood
// just executing at five times instead of initializing it and executing it.
function foo() { }

for (let i = 0; i < 5; i++) {	
  foo();
}

② returning parameter of function.


function foo(param) {
  return param; 
}

foo(); 
// undefined
// parameter is nothing!

⏬ Default Parameter!!

function foo(param = 1) {
  return param; 
}

foo(); // 1
profile
매일 성장하는 프론트엔드 개발자

0개의 댓글