- 2024년 2월 2일 작성하여 벨로그에서 이전한 글.
지난주에 자바스크립트 함수에 대하여 공부했는데, 내용이 많아서 이번주에 보충공부를 했다.
Function() 생성자
함수는 Function() 생성자 통해서도 만들 수 있다. 변수에 생성자를 호출하여 익명함수의 형태이며 생성자 호출 시 함수 몸체를 분석(parse)하여 새로운 함수 객체를 생성한다.
Function() 생성자가 가진 가장 큰 특징은 동적으로 자바스크립트 함수를 생성할 수 있다는 점이다. 런타임에 동적으로 함수의 내용이 생성되어야 할 때를 제외하고는 일반적으로 사용하는 방법은 아니고, 보통은 함수 선언문 또는 함수 표현식을 많이 사용한다.
let sc = "outer";
function constructFunc() {
let sc = "inner";
return new Function("return sc");
}
constructFunc()(); // outer
화살표 함수
화살표 함수는 함수 표현식을 더 간결하게 작성할 수 있어서 가독성이 좋다. 특히 한 줄짜리 콜백 함수를 사용할 때, 화살표 함수는 코드의 길이를 꽤 많이 줄여준다.
const normalAdd2 = function(x) {return x+2}
const arrowAdd2 = x => x+2
normalAdd2(2) // 4
arrowAdd2(2) // 4
// 매개변수가 있을 때 괄호 생략 가능
// return 생략 가능
객체의 메서드로 화살표 함수를 사용하면 메서드 내에서 일반적인 this와 달리 this를 일관되게 사용할 수 있다.
const ThisTest = {
name: "other",
inner: function() {
const innerFunc = {
name: "inner",
innerNormal: function() {console.log("inner normal:",this.name);},
innerArrow: ()=> {console.log("inner arrow:",this.name);}
}
return innerFunc.innerNormal(), innerFunc.innerArrow();
},
otherNormal: function() {console.log("other normal:",this.name)},
//== otherNormal() {console.log("other normal:",this.name)},
otherArrow: ()=> {console.log("other arrow:",this.name);}
}
ThisTest.inner(); // inner normal: inner, inner arrow: other
ThisTest.otherNormal(); // other normal: other
ThisTest.otherArrow(); // other arrow:
함수선언문과 화살표 함수 차이점
함수 선언문은 자신의 this를 가리키지만, 화살표 함수는 자신을 둘러싼 스코프의 this를 상속받는다.
// 함수 선언문
function regularFunction() {
console.log(this);
}
// 화살표 함수
const arrowFunction = () => {
console.log(this);
}
regularFunction(); // window 객체를 가리킴
arrowFunction(); // 상위 스코프의 this를 상속받음
함수 선언문에서는 arguments 객체를 사용할 수 있지만, 화살표 함수에서는 사용할 수 없다. 화살표 함수에서는 명시적으로 파라미터를 정의해야 한다.
function regularFunction() {
console.log(arguments);
}
const arrowFunction = () => {
console.log(arguments); // 에러 발생: arguments는 화살표 함수 내에서 사용할 수 없음
}
regularFunction(1, 2, 3); // 출력: [1, 2, 3]
arrowFunction(1, 2, 3); // TypeError: arguments is not defined
함수 선언문은 호이스팅에 의해 스크립트가 실행되기 전에 이미 생성되어 어디서든 호출이 가능하다. 화살표 함수는 런타임에 정의된다. 따라서 정의된 이후에만 호출할 수 있다.
regularFunction(); // 정상 실행
arrowFunction(); // TypeError: arrowFunction is not a function
function regularFunction() {
console.log('Regular function');
}
const arrowFunction = () => {
console.log('Arrow function');
}
함수 선언문으로 생성된 함수는 prototype 속성을 가지며, 이를 통해 새로운 객체의 프로토타입으로 사용할 수 있다. 화살표 함수는 prototype 속성을 가지지 않는다.
unction regularFunction() {}
const arrowFunction = () => {}
console.log(regularFunction.prototype); // RegularFunction {}
console.log(arrowFunction.prototype); // undefined
함수 선언문은 생성자로 사용할 수 있지만, 화살표 함수는 생성자로 사용이 불가능하다.
function RegularConstructor() {}
const ArrowConstructor = () => {};
const regularInstance = new RegularConstructor(); // RegularConstructor 인스턴스 생성
const arrowInstance = new ArrowConstructor(); // TypeError: ArrowConstructor is not a constructor
'프로그래밍 > Javascript' 카테고리의 다른 글
[모던 자바스크립트 Deep Dive] 브라우저 렌더링 과정 (0) | 2024.08.27 |
---|---|
[JS] 변수: var, let, const (0) | 2024.05.28 |
[Javascript] 함수 선언, 함수 표현, 객체의 메서드 (0) | 2024.04.17 |
[Javascript] 비동기 처리: Promise객체, fetch, async / await (0) | 2024.04.09 |