반응형
Arrow function
ES6 문법 중 하나
this, arguments, super 또는 new.target을 바인딩하지 않음
항상 익명
메소드 함수가 아닌 곳에 적합 - 생성자로 사용할 수 없음.
Arrow function 선언
// 함수 표현식
function() { ... }
// 화살표 함수 표현식
() => { ... }
// 매개변수 지정 방법
() => { ... } // 매개변수가 없을 때
num => { ... } // 매개변수가 하나일 때, 소괄호 생략 가능
// implicit return → 함수와 return 식이 한줄이면, 중괄호{}를 생략하고 암묵적으로 return 된다.
num => { return num++ }
num => num++ // 위 표현과 동일
() => { return { x : 1 } ; }
() => ({ x : 1 }) // 위 표현과 동일, 소괄호()를 사용하여 return
Arrow function 호출
const arr = [1,2,3]
const useMap = arr.map(num => num + num);
console.log(useMap); // [2, 4, 6]
This를 바인딩 하지 않음
콜백 함수 내부의 this는 전역 객체인 window를 가리킴.
<body>
<button>Click me</button>
<div>Click me</div>
<script>
const button = document.querySelector("button");
const div = document.querySelector("div");
button.addEventListener("click", function () {
console.log(this); // <button>button</button>
});
div.addEventListener("click", () => {
console.log(this); // Window obj
});
</script>
</body>
메소드 함수가 아닌 곳에 적합
메소드(Method) : Object {객체} 안에서의 함수식을 메소드라 표현한다.
(일반 함수와 구분하기 위함)
const obj = {
num : 10,
b : ()=> {
console.log(this.num) // this는 window
},
c : function() {
console.log(this.num) // this는 obj
}
}
obj.b() //undefined
obj.c() //10
반응형