Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Functions #34

Closed
raycon opened this issue Dec 28, 2020 · 0 comments
Closed

Functions #34

raycon opened this issue Dec 28, 2020 · 0 comments

Comments

@raycon
Copy link
Owner

raycon commented Dec 28, 2020

Function

자바스크립트에서 모든 함수는 Function 객체다. 다른 객체들 처럼 속성 및 메소드를 가질 수 있는 일급 객체다.

함수 선언

Function declarations

함수 정의(definition), 함수 선언(function declaration), 함수 구문(function statement)은 function 키워드를 상요한다.

function name([param[, param[, ... param]]]) {
   statements
}

이렇게 선언된 함수는 호이스팅된다.

console.log(square(5));
/* ... */
function square(n) { return n * n }

함수는 그 함수가 선언된 함수를 스코프로 갖는다. 만약 중첩 없이 코드의 탑 레벨에 함수가 정의된 경우, 전체 프로그램을 스코프로 갖는다.

Function expressions

함수 표현식으로 함수를 선언할 수 있다. 표현식으로 정의된 함수는 호이스팅 되지 않는다.

// 익명 함수 표현식
const square = function(number) { return number * number }
var x = square(4) // x gets the value 16

// 네임드 함수 표현식 (재귀 가능)
const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1) }
console.log(factorial(3))

파라미터 전달

함수의 파라미터는 으로 전달된다. 파라미터의 값을 변경해도 원래 값은 변하지 않는다. 하지만 객체가 전달된 경우 객체의 속성은 변경될 수 있다.

Method

함수가 객체 안에 속성으로 있을 경우, 이를 메소드라고 부른다.

Scope

함수 안에 선언된 변수는 함수의 외부에서 접근할 수 없다. 함수는 함수 외부의 변수에 접근할 수 있다.

arguments 객체

함수에 전달된 인수를 arguments를 사용해서 배열과 비슷한 방식으로 사용할 수 있다.

  • arguments: 현재 실행 중인 함수에 전달된 인수를 포함하는 배열 같은 객체.
  • arguments.callee : 현재 실행 중인 함수.
  • arguments.caller : 현재 실행 중인 함수를 호출한 함수.
  • arguments.length: 함수에 전달된 인수의 수.
arguments[i]

arguments는 배열이 아니다.

Function parameters

Default parameters

ECMA2015 이후로 파라미터에 기본 값을 지정할 수 있다. 지정하지 않을 경우 undefined 값을 갖는다.

function multiply(a, b = 1) {
  return a * b;
}

multiply(5); // 5

Rest parameters

함수의 마지막 파라미터의 앞에 ...를 붙여서 나머지 모든 인수를 자바스크립트 배열로 대체한다.

arguments와 달리 Rest 파라미터는 Array 인스턴스다.

function multiply(multiplier, ...theArgs) {
  return theArgs.map(function(element) {
    return multiplier * element;
  });
}

var arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]

Arrow functions

함수 표현식과 비교해서 짧은 문법으로 함수를 선언할 수 있다. 화살표 함수는 자체적인 this, arguments, super, new.target을 갖지 않는다. 화살표 함수는 항상 익명이다.

@raycon raycon added the JS label Dec 28, 2020
@raycon raycon added this to the JavaScript Concepts milestone Dec 28, 2020
@raycon raycon closed this as completed Dec 29, 2020
@raycon raycon reopened this Dec 30, 2020
@raycon raycon added the done label Dec 30, 2020
@raycon raycon closed this as completed Dec 30, 2020
@raycon raycon removed the done label Dec 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant