Search
Duplicate

화살표 함수

생성일
2023/01/23 03:48
태그
javascript

화살표 함수

function add1(x, y) { return x + y; } // --> const add2 = (x, y) => { return x + y; }; const add3 = (x, y) => x + y; const add4 = (x, y) => (x + y); function not1(x) { return !x; } // --> const not2 = x => !x;
JavaScript
복사
화살표 함수가 생기고 기존 function이 사라지지 않는 이유?
→ this 때문
var relationship1 = { name: 'zero', friends: ['nero', 'hero', 'xero'], logFriends: function () { var that = this; this.friends.forEach(function (friend) { console.log(that.name, friend); }); }, }; relationship1.logFriends(); // -----> 화살표 함수 const relationship2 = { name: 'zero', friends: ['nero', 'hero', 'xero'], logFriends() { this.friends.forEach(friend => { console.log(this.name, friend); }); }, }; relationship2.logFriends();
JavaScript
복사

화살표 함수가 기존 function() {}을 대체하는 건 아님 (this 가 달라짐)

logFriends 메서드의 this 값에 주목
forEach의 function의 this와 logFriends의 this는 다름
that이라는 중간 변수를 이용해서 logFriends의 this를 전달
—>

forEach의 인자로 화살표 함수가 들어간 것에 주목

forEach의 화살표함수의 this와 logFriends의 this가 같아짐
화살표 함수는 자신을 포함하는 함수의 this를 물려받음
물려받고 싶지 않을 때 : function(){}을 사용

this를 쓸거면, function()을 쓰고, 그 이외는 다 화살표 함수로 통일

this; button.addEventListener('click', function(e) { console.log(this.textContent); }); //// button.addEventListener('click', (e) => { console.log(e.target.textContent); });
JavaScript
복사