자바스크립트 JS - 화살표함수

hyunnu·2021년 7월 19일
0
post-thumbnail

화살표 함수

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;

객체를 리턴하는 경우에는 소괄호는 필수이다.

const obj = (x, y) => ({x, y})

ex 1)

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();

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

  • forEach의 function의 this와 logFriends의 this는 다름
  • that이라는 중간 변수를 이용해서 logFriends의 this를 전달
var relationship2 = {
    name: 'zero',
    friends: ['nero', 'hero', 'xero'],
    logFriends() {
        this.friends.forEach(friend => {
            console.log(this.name, friend);
        });
    },
};
relationship2.logFriends();

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

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

ex 2) tag에 event 달아줄 때

button.addeventListener('click', function() {
	console.log(this.textContent);// 자신의 this
});
=> 버튼을 클릭하면 단어가 출력

하지만,

button.addeventListener('click', () => {
	console.log(this.textContent);// 부모의 this라서(자신의 this x)
});
=> 동작 안함

화살표 함수를 쓰려면,

button.addeventListener('click', (e) =>{
	console.log(e.target.textContent);
});
                   
profile
Data Engineer / Back-End Developer

0개의 댓글