일반 함수
자바스크립트의 가장 기본적인 형태의 함수. 함수 선언식 또는 함수 표현식으로 정의되며, 컨텍스트 없이 호출될 경우 this가 전역 객체를 가리킨다. 객체의 메서드로 호출되면 this는 해당 객체를 가리킨다.
정의 방법
함수 선언식
function sayHello() {
console.log("Hello!");
}
함수 표현식
const sayHello = function() {
console.log("Hello!");
};
기본적인 호출
sayHello(); // "Hello!"
this의 동작
전역 호출
function showThis() {
console.log(this);
}
showThis(); // 전역 객체 (window or global)
객체의 메서드로 호출
const obj = {
name: "Alice",
showThis: function() {
console.log(this);
}
};
obj.showThis(); // obj 객체
함수 내부에서 호출
const obj = {
name: "Alice",
showThis: function() {
function innerFunc() {
console.log(this);
}
innerFunc();
}
};
obj.showThis(); // 전역 객체 (window or global)
innerFunc는 일반함수로 호출되기 때문에 this는 전역 객체를 가리킨다.
일반 함수 vs 화살표 함수
일반 함수
- 자신만의 this를 가진다
- 호출 문맥에 따라 this의 값이 결정된다.
화살표 함수
- 자신만의 this가 없다.
- 화살표 함수가 정의된 렉시컬 환경에서의 this를 상속 받는다.
const obj = {
name: "Alice",
showThis: function() {
const arrowFunc = () => {
console.log(this); // 화살표 함수는 외부의 `this`를 상속
};
arrowFunc();
}
};
obj.showThis(); // obj 객체
일반 함수 vs 메서드
일반 함수 : 단독으로 호출되거나 객체와 관계 없이 정의된 함수.
메서드 : 객체 내에 정의된 함수. 호출 시 this는 해당 객체를 가리킴.
function greet() {
console.log("Hello");
}
const person = {
greet: function() {
console.log("Hi");
}
};
greet(); // 일반 함수 호출
person.greet(); // 메서드 호출