Function과 관련된 ES6+문법을 알아보자
Arrow Function(화살표 함수)은 기본 함수 표현식보다 구문이 짧기 때문에 짧게 함수를 표현 할 때 사용하기 좋다 (가독성이 좋다)
Arrow Function은 보통 익명 함수를 사용하기 적합한 곳에 사용하기 좋다
const name = {"caya", "kaiman", "lynn", "hermion" };
// {} 사용
name.map((e) => {
console.log(e.length);
}); // 4, 6, 4, 7
// {} 미사용
name.map(e => console.log(e.length)); // 4, 6, 4, 7
화살표 함수는 Parameter(매개 변수)가 두 개 이상일 경우만 ()로 감싸고 아닌경우는 안써도 된다
const name = {"caya", "kaiman", "lynn", "hermion" };
// {} 미사용
name.map(e,idx => console.log(`${idx+1}번 째 이름의 길이: ${e.length}`)); // 오류
name.map((e,idx) => console.log(`${idx+1}번 째 이름의 길이: ${e.length}`));
/*
0번 째 이름의 길이: 4
1번 째 이름의 길이: 6
2번 째 이름의 길이: 4
3번 째 이름의 길이: 7
*/
화살표 함수를 {} 없이 사용하면 => 이후 코드가 자동으로 return 된다
const name = {"caya", "kaiman", "lynn", "hermion" };
// 자동으로 return
console.log(name.map(e => console.log(e.length))); // 4, 6, 4, 7
// return을 적어야 함
console.log(
name.map((e) => {
e.length;
})
); // [undefined, undefined, undefined, undefined]
화살표 함수는 자신을 둘러싸고 있는 상위 환경의 this를 그대로 계승하는 Lexical this를 따른다
때문에 아래와 같은 상황일 경우엔 사용에 주의해야 한다
const info = {
name: "jcy",
age: 28,
sayHello: () => console.log(`hello ${this.name}`),
};
info.sayHello(); // hello
기대했던 hi jcy가 아닌 hi가 출력된다
따라서 메소드로 사용 시 this로 해당 객체를 얻어야 할 경우 일반함수를 사용하자
const info = {
name: "jcy",
age: 28,
};
Object.prototype.sayHello = () => console.log(`hello ${this.name}`);
info.sayHello(); // hello
메소드와 결과가 동일하다 마찬가지로 일반함수를 사용하자
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log(this); // 클릭시 window가 출력
});
this에 button이 아닌 window가 들어오기 때문에 this로 해당 버튼을 핸들하려면 일반함수를 사용하자
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
default value는 함수 선언시 매개 변수에 넣는 기본 값을 말한다
const myName = "정찬영";
const sayHello = function (name = myName) {
console.log(`hello ${name}`);
};
sayHello(); // hello 정찬영
인자가 주어지지 않았지만 default value로 인해 hello 정찬영이 출력되는 모습이다
끝 ! 🐮