화살표함수

0

javascript

목록 보기
2/8

함수

const double = function(x) {
	return x * 2;
}
console.log('double: ', double(7));

화살표함수

const doubleArrow = (x) => {
	return x * 2;
}
console.log('doubleArrow: ', doubleArrow(7));

매개변수가 1개, 함수가 1줄일 때
위 코드는 아래와 같이 축약 가능하다.

const doubleArrow = x => x * 2;
console.log('doubleArrow: ', doubleArrow(7));

축약형으로 객체데이터를 반환할 때에는
함수 실행 중괄호와 혼동될 수 있으니, 소괄호로 감싸주어야 한다.

const doubleArrow = x => ({ number: x });
console.log('doubleArrow: ', doubleArrow(7));

this

일반 함수의 this

일반 함수는 호출 위치에서 this를 정의한다.

화살표함수의 this

화살표 함수는 자신이 선언된 함수 범위에서 this를 정의한다.

const erun - {
	name: 'erun',
    normal: function(){
    	console.log(this.name);
    },
    arrow: () => {
    	console.log(this.name);
    }
}

erun.normal(); 	// 'erun' 출력
erun.arrow(); 	// undefined 출력
profile
를 질투하는 그냥 개발자입니다.

0개의 댓글