JavaScript
화살표 함수
SMASMC
2023. 12. 30. 05:19
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;
=> 를 사용함으로써 function의 기능을 하기에 return 및 function을 작성하지 않아서 코드가 간결해진다.
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();
console.log('아래는 relationship2입니다.');
const relationship2={
name:'zero',
friends:['nero','hero','xero'],
logFriends(){
this.friends.forEach(friend=>{
console.log(this.name,friend);
});
}
}
relationship2.logFriends();
- 함수 스코프인 this를 사용하여 함수를 내부에서 호출하여 사용할 수 있다.
- 함수 스코프 : * 함수가 호출될 때마다 해당 함수 내에서 사용되는 변수들은 함수 스코프에 속하고, 함수 외부에서는 접근할 수 없다.