javascript, jQuery & Node.js/Node.js 사용전 자바스크립트
화살표 함수 function을 화살표로 사용 => / ES2015 & ES6 - 04
yy_dd2
2022. 5. 6. 22:34
반응형
//화살표 함수
// 여기서 function 대신 => 기호로 함수를 선언한다
function add1(x, y) {
return x + y;
}
const add2 = (x, y) => {
return x + y;
}
// 화살표 함수 안에 return 문만 있다면 더 줄일 수 있다
const add3 = (x, y) => x + y;
// 소괄호로 줄일 수 있다
const add4 = (x, y) => (x + y);
function not1(x) {
return !x;
}
// 매개변수가 한 개면 소괄호로 묶지 않아도 된다
const not2 = x => !x;
this 바인딩의 방식도 쉽게 바꼈다
// this 바인드 방식
// 기존방식
var relationship1 = {
name: 'zero'
,friends: ['nero', 'hero', 'xero']
,logFriends:function(){
var that = this; // relationship1 을 가리키는 this 를 that에 저장
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();
반응형