JS 전문가되기 제목의 포스팅의 목적은 필자가 공부한 것을 복습하는데 그리고 약점을 보완하는데 있습니다.
ES6에서 추가된 문법으로 보통의 함수 표현 방법을 축약해준다.
// 함수 표현식 const add = function(x, y) { return x + y }; // 함수 표현식 (arrow) const add = (x, y) => { return x + y }; const add = (x, y) => x + y;
주의!
1. call, apply, bind를 사용할 수 없습니다.
2. 화살표 함수의 실행은 this를 결정짓지 않습니다.
함수 실행시 호출 방법에 따라 결정되는 객체
// function function makeCounter() { return { value: 0, increase: function() { this.value++ }, decrease: function() { this.value-- }, getValue: function() { return this.value; } } } // class class Counter { constructor() { this.value = 0; } increase() { this.value++ } decrease() { this.value-- } getValue() { return this.value } } //
call, apply는 this를 지정해서 함수를 실행할 때 사용한다.
첫번째 인자는 this가 들어가고, 두번째 인자는 함수의 매개변수가 들어간다.
단! 이때 apply의 두번째 인자는 배열의 형태를 사용한다.
Math.max.call(null, 5, 4, 1, 6, 2) // 6 Math.max.apply(null, [5,4,1,6,2]) // 6
bind는 this를 지정하는데 사용하지만 함수를 실행시키지 않는다.
(parameter를 지정할 수도 있음)