화살표 함수와 function
기초/JavaScript2021. 9. 6. 20:52
function add1(x,y) {
return x + y;
}
const add2 = (x,y) => {
return x + y;
}
위의 함수 add1은 아래의 add2처럼 간단하게 작성할 수 있다.
함수의 이름은 변수명으로 적어 주고, function 자체는 =>로 대체된다.
add2처럼 중괄호 다음에 바로 return이 나오면 중괄호는 생략할 수 있다.
const add2 = (x,y) => {
return x + y;
}
const add3 = (x,y) => x+y;
이렇게! add1, add2, add3는 결국 다 같은 함수를 나타낸다.
헷갈릴 수 있기 때문에 return값은 한 번 더 괄호로 묶어 주기도 한다.
function not1(x) {
return !x;
}
const not2 = (x) => !x;
const not3 = x => !x;
마찬가지로 not1과 not2, not3는 다 같은 함수지만 다르게 나타낼 수 있다.
단, 매개변수가 한 개일 때는 not3처럼 x를 괄호로 감싸지 않고도 나타낼 수 있다.
화살표 함수는 이것만 조심하자 ↓
객체를 리턴하는 경우에는 소괄호가 필수다.
const obj = (x,y) => {
return {x:x, y:y};
};
const obj = (x,y) => {x,y};
const obj = (x,y) => ({x,y});
맨 위의 함수를 두 번째와 같이 생략을 해버리면
결국 우변이 함수의 body인지 객체의 리터럴을 의미하는 건지 구별할 수 없다.
곧바로 객체를 리턴하는 경우에만 세번째처럼 소괄호를 필수로 넣어 주는 게 좋다.
function이 왜 계속 사용되는가?
<relationship1(기존 function)의 경우>
var relationship1 = {
name: "doodoo",
friends: ["booboo", "soosooo", "joojoo"],
logFriends: function() {
var that = this; //relationship1을 가리키는 this를 that에 저장
this.friends.forEach(function(friend){
console.log("that");
console.log(that.name, friend);
console.log("this");
console.log(this.name, friend);
});
},
};
relationship1.logFriends();
function은 각각 자신만의 this를 가진다.
부모의 this를 받기 위해서는 that 또는 self와 같은 변수에 저장해서 사용해야 한다.
<relationship2(화살표 함수=lambda식 함수)의 경우>
const relationship2 = {
name: "doodoo",
friends: ["booboo", "soosoo", "joojoo"],
logFriends(){
this.friends.forEach((friend) => {
console.log(this.name, friend);
});
},
};
relationship2.logFriends();
자기만의 this를 가지지 않고 무조건 부모 function의 this를 물려받는다.
= 본인의 this를 사용할 수 없다.
참조 : 제로초(zerocho)님 인프런 강의
'기초 > JavaScript' 카테고리의 다른 글
구조분해 할당 (0) | 2021.09.06 |
---|---|
var, const, let (0) | 2021.09.06 |
호출 스택, 이벤트 루프 (0) | 2021.09.02 |
댓글()