function 함수명() {
// 로직..
};
함수명();
const main = function () {
// 로직..
};
main();
함수 선언식은 함수 전체를 호이스팅 한다. 작성한 위치와 상관없이 호이스팅 되어 최상단으로 끌어 올려진다. 따라서 함수 선언 전에 함수를 호출해도 정상적으로 호출이된다.
함수 표현식은 별도의 변수에 할당하는데, 호이스팅에 영향을 받지 않는다.
main(); // o
function main() {
// 로직..
};
main(); // x
const main = function () {
// 로직..
};
const arrowFunction = () => {
// 로직..
};
일반 함수에서의 this
const obj = {
value: 42,
regularFunction: function() {
console.log(this.value);
}
};
obj.regularFunction(); // 42
위 코드에서 regularFunction은 obj의 메서드로 호출되므로 this는 obj를 가리키고, value 속성의 값인 42가 출력된다.
하지만 일반 함수로 호출하면 this가 다르게 바인딩된다.
const regularFunc = obj.regularFunction;
regularFunc(); // undefined (또는 전역 객체의 속성)
이 경우, regularFunc는 일반 함수로 호출되기 때문에 this는 전역 객체를 가리키거나 strict mode에서는 undefined가 된다.
화살표 함수에서의 this
const objArrow = {
value: 42,
arrowFunction: () => {
console.log(this.value);
}
};
objArrow.arrowFunction(); // undefined
위의 화살표 함수에서 this는 objArrow가 아닌, 화살표 함수가 정의된 외부 스코프의 this를 사용한다. 이 경우, 일반적인 환경에서는 전역 객체를 가리키므로 undefined가 출력된다.
화살표 함수의 this 유지
const objContext = {
value: 42,
regularFunction: function() {
const innerArrowFunction = () => {
console.log(this.value);
};
innerArrowFunction(); // 42
}
};
objContext.regularFunction(); // 42
여기서 innerArrowFunction은 regularFunction의 this를 정적으로 사용하여 42를 출력한다.
일반 함수에서의 arguments
function regularFunction() {
console.log(arguments); // 모든 인수를 출력
console.log(arguments[0]); // 첫 번째 인수 출력
}
regularFunction(1, 2, 3); // [1, 2, 3], 1
위 코드에서 regularFunction에 세 개의 인수를 전달하면 arguments 객체가 생성되고, 배열처럼 인수에 접근할 수 있다.
화살표 함수에서의 arguments
const arrowFunction = (...args) => {
console.log(args); // 모든 인수를 출력
console.log(args[0]); // 첫 번째 인수 출력
};
arrowFunction(1, 2, 3); // [1, 2, 3], 1
...args를 사용하여 전달된 인수들을 배열로 받을 수 있다. 결과는 일반 함수와 동일하게 출력된다.
일반 함수에서의 new 키워드
function Person(name) {
this.name = name;
}
const person1 = new Person('Alice');
console.log(person1.name); // Alice
위 코드에서 Person 함수는 생성자 함수로 사용되며, new 키워드로 호출할 때 새로운 객체가 생성된다. this는 새로 생성된 객체를 가리키게 된다.
화살표 함수에서의 new 키워드
const PersonArrow = (name) => {
this.name = name; // this는 바인딩되지 않음
};
try {
const person2 = new PersonArrow('Bob'); // TypeError 발생
} catch (error) {
console.log(error.message); // PersonArrow is not a constructor
}
위 코드에서 PersonArrow는 화살표 함수이다. new 키워드와 함께 호출하려고 하면 TypeError가 발생하며, "is not a constructor"라는 에러 메시지가 출력된다.