# Function 생성자 함수
자바스크립트가 기본 제공하는 빌트인 함수인 Function 생성자 함수에 매개변수 목록과 함수 몸체를 문자열로 전달하면서 new 연산자와 함께 호출하면 함수 객체를 생성해서 반환한다.
new 연산자 없이 호출해도 결과는 동일하다.
생성자 함수란?
생성자 함수는 객체를 생성하는 함수를 말한다. 생성자 함수에 대한 자세한 내용은 뒤에서 다룰 예정이다!
var add = new Function('x', 'y', 'return x+y');
console.log(add(2, 5)); // 7
Function 생성자 함수로 함수를 생성하는 방식은 일반적이지 않고 바람직하지도 않다. 그 이유는 무엇일까?
클로저(closure)를 생성하지 않는 등, 함수 선언문이나 함수 표현식으로 생성한 함수와 다르게 동작하기 때문이다.
# 화살표 함수(arrow function)
ES6에서 도입된 화살표 함수는 function 키워드 대신 화살표(fat arrow) => 를 사용해 좀 더 간략한 방법으로 함수를 선언한다. 화살표 함수는 항상 익명함수로 정의한다.
const add = (x, y) => x+ y;
console.log(add(3, 4)); // 7
화살표 함수는 기존의 함수보다 표현만 간략한 것이 아니라 내부 동작 또한 간략화 되어있다.
- 생성자 함수로 사용할 수 없다
- 기존 함수와 this 바인딩 방식이 다르다
- prototype 프로퍼티가 없다
- arguments 객체를 생성하지 않는다.
퀴즈
- Function 생성자 함수는 함수 선언문이나 함수 표현식으로 생성한 함수와 다르게 동작한다. (O, X)
더보기
정답: O
- 화살표 함수는 항상 익명함수로 정의한다. (O, X)
더보기
정답: O
- 화살표 함수는 생성자 함수로 사용할 수 있다. (O, X)
더보기
정답: X
화살표 함수는 생성자 함수로 사용할 수 없다.
- 화살표 함수는 prototype 프로퍼티가 없다. (O,X)
더보기
정답: O
'JavaScript' 카테고리의 다른 글
[JavaScript] 함수 - 참조에 의한 전달과 외부 상태의 변경 (2) | 2023.10.27 |
---|---|
[JavaScript] 함수 - 함수 호출 (2) | 2023.10.27 |
[JavaScript] 함수 - 함수 생성 시점과 함수 호이스팅 (0) | 2023.10.27 |
[JavaScript] 함수 - 함수를 사용하는 이유, 함수 리터럴, 함수 정의 (0) | 2023.10.23 |
[JavaScript] 프로퍼티 어트리뷰트 (0) | 2023.10.20 |