일반 함수와 화살표 함수의 차이점

LeeJaeHoon·2022년 4월 5일
0
post-thumbnail

화살표 함수

화살표 함수

자바스크립트에서는 함수또한 값이기 때문에 변수나 상수에 담아서 사용이 가능합니다.

const hello = function() {
	return "hi";
}
console.log(hello()) //hi

이것을 함수 표현식이라고 부릅니다.

함수 표현식을 보다 단순하고 간결한 문법으로 함수를 만들 수 있는 방벙이 있습니다. 바로 화살표 함수를 사용하는 것입니다.

const hello = () => {
	return "hi";
}
console.log(hello()) //hi

화살표 함수가 return만 할 경우 { }을 생략할 수 있습니다.

const hello = () => "hi"
console.log(hello()) //hi

함수에 인자가 하나만 들어가는 경우 괄호를 생략 할 수 있습니다.

const hello = name => `My name is ${name}`
console.log(hello("JaeHoon")) //My name is JaeHoon

일반 함수와 화살표 함수의 차이점

01 this를 가지지 않는다

일반 함수를 메서드로 호출했을때

let nodeStudy = {
	time: "오후 6시",
	whenMeet() {
		return this.time;
	}
}
console.log(nodeStudy.whenMeet()); //오후 6시

화살표 함수를 메서드로 호출했을 때

let nodeStudy = {
	time: "오후 6시",
	whenMeet: () => this.time;
}
console.log(nodeStudy.whenMeet()); // undefined

02 new와 함께 호출할 수 없다

생성자 함수

function Human(name) {
	this.name = name;
}
const me = new Human("jaehoon");
console.log(me.name); // jaehoon

화살표 함수는 this가 없기 때문에 생상자 함수로 사용할 수 없다는 제약이 있습니다.

const Human = (name) => {
	this.name = name;
};
const me = new Human("jaehoon"); // Error

03 arguments 사용 가능 여부

일반 함수에서는 함수가 실행 될때 암묵적으로 arguments변수가 전달되어 사용할 수 있습니다.

function fun() {
  console.log(arguments);
}

fun(1, 2, 3); // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]

화살표 함수에서는 arguments변수가 전달되지 않습니다.

0개의 댓글