제일 최신 문법 인 Arrow function을 위주로 설명한다.
ES6에서 추가된 새로운 함수 표현식입니다. 간단한 함수를 만들 때 유용합니다.
let functionName = (parameter1, parameter2, ...) => {
return parameter1 + parameter2;
};
let functionName = parameter1 => {
return parameter1 * 2;
};
let functionName = parameter1 =>
return parameter1 * 2;
함수 이름과 매개변수를 지정하여 함수를 만드는 가장 일반적인 방법입니다. 함수 선언문은 함수를 선언하기 이전에 호출해도 실행됩니다.
function functionName(parameter1, parameter2, ...) {
return parameter1 + parameter2;
}
함수 선언문에는 세미클론이 없습니다!
변수에 함수를 할당하여 함수를 만드는 방법입니다. 함수 표현식은 변수가 선언된 이후에만 호출할 수 있습니다.
var functionName = function(parameter1, parameter2, ...) {
return parameter1 + parameter2;
};
함수표현식에는 세미클론이 있습니다.
Arrow Function
과 Function Declaration
의 가장 큰 차이 중 하나는 this 바인딩입니다.
Function Declaration
에서 함수가 호출될 때마다 this
값이 동적으로 결정됩니다. this
는 호출되는 컨텍스트에 따라 결정되며, 함수를 메서드로 사용하는 경우, 메서드를 호출한 객체가 this
가 됩니다.const obj = {
name: 'object',
getName: function() {
console.log(this.name); // 'object'
}
}
obj.getName();
위 코드에서 getName
메서드는 Function Declaration
으로 정의되어 있습니다. getName
이 호출되는 시점에서 this
값은 obj
객체를 참조하게 됩니다. 따라서 object
가 출력됩니다.
하지만, getName
메서드를 다른 객체에서 호출하면 this
값은 호출한 객체를 참조하게 됩니다.
const anotherObj = {
name: 'another object'
}
obj.getName.call(anotherObj); // 'another object'
Arrow Function
은 함수를 선언할 때 this
를 바인딩하며, 실행 중에 this
값이 변경되지 않습니다. Arrow Function
에서 this
값은 선언 시점에 정적으로 결정되며, 상위 스코프의 this
값을 그대로 참조합니다.아래 예시를 통해 더 자세히 살펴보겠습니다.
const obj = {
name: 'object',
getName: function() {
console.log(this.name); // 'object'
const arrowFunction = () => {
console.log(this.name); // 'object'
}
arrowFunction();
function normalFunction() {
console.log(this.name); // undefined
}
normalFunction();
}
}
obj.getName();
위 예시에서 getName
메서드는 Function Declaration
으로 정의되었으며, arrowFunction
은 Arrow Function
으로 정의되었습니다. arrowFunction
내부의 this
값은 getName
의 this
값을 그대로 참조하므로 object
가 출력됩니다.
반면 normalFunction
은 Function Declaration
으로 정의되었으며, 호출 시점의 this
값에 따라 동적으로 바인딩됩니다. 따라서 normalFunction
내부의 this
값은 undefined
가 됩니다.
하지만, arrowFunction
을 전역 스코프에서 선언하면 this
값은 전역 객체를 참조하게 됩니다. 다음과 같이 코드를 작성하면 this
값은 전역 객체를 참조하게 됩니다.
const arrowFunction = () => {
console.log(this); // Window {...}
}
arrowFunction();
Arrow Function
은 함수를 선언할 때 this
값을 결정하기 때문에, bind
, call
, apply
와 같은 메서드로 this
값을 변경할 수 없습니다.