1. this
1) 일반함수 안에서 this는 자기 자신을 가리킨다.
=>일반함수 안의 중첩함수 안에서 부모 함수를 가리키려면 중간다리 역할이 필요하다.
var relationship1 = {
name: 'zero'
friends: ['nero', 'hero', 'xero']
logFriends: function(){
var that = this
this.friends.forEach(function(friend){
console.log(that, name, friend)
})
}
}
2) 화살표함수 안에서 this는 부모함수를 가리킨다.
var relationship2 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends(){
this.friends.forEach(friend => {
console.log(this.name, friend)
})
},
}
relationship2.logFriends()
2. 화살표함수의 간략화
1) 매개변수가 하나일 때는 ( )생략 가능
2) 실행문이 하나일 때는 { } 생략 가능
3) 객체를 리턴할 때는 객체 소괄호가 필수이다. ( ) =>( { } )
* this를 쓸거면 일반함수 사용
* this를 안 쓸 때는 화살표 함수 사용
this
button.addEventListener('click', (e)=>{
console.log(this.textContent)
}
button.addEventListener('click', function(){
console.log(this.textContent)
})
button.addEventListener('click', (e) => {
console.log(e.target.textContent)
})
728x90
'Node.js' 카테고리의 다른 글
비동기 : Promise (0) | 2023.06.28 |
---|---|
class (0) | 2023.06.28 |
구조분해할당 (0) | 2023.06.28 |
호출스택 (0) | 2023.06.28 |
Node.js 의 정의 (0) | 2023.06.28 |