화살표 함수는 this를 새로 바인딩하지 않는다. 

 


기존 

var character = {
    eq : ['투구', '귀걸이', '손무기', '손방패', '갑옷', '각반', '장갑'] , 
    print : function( delay = 1000 ) {
    	setTimeout( function() {
        	console.log( this.eq.join(",") ) 
        } , delay ) 
    } 
}

character.print()

 

결과) 

Uncaught TypeError: Cannot read property 'join' of undefined
 

 

해당 경우 this는 window 객체를 가리킨다. 

그렇기 때문에 오류로 Uncaught TypeError: Cannot read property 'join' of undefined가 나온다.

 

delay는 파라미터 기본 값이다. 

(포스팅 참고 : 2019/06/26 - [ES6] - ES6 - 함수 파라미터 기본값(디폴트값) 적용하기 ) 

 


화살표 함수 방식 

새로운 this영역을 만들지 않는다. 

var character = {
    eq : ['투구', '귀걸이', '손무기', '손방패', '갑옷', '각반', '장갑'] , 
    print : function( delay = 1000 ) {
    	setTimeout( () => {
        	console.log( this.eq.join(",") ) 
        } , delay ) 
    } 
}

character.print()

 

결과) 

투구,귀걸이,손무기,손방패,갑옷,각반,장갑

 


화살표 함수 방식 주의점 

print 프로퍼티를 화살표 함수로 바꾸면 this는 window객체가 된다. 

var character = {
    eq : ['투구', '귀걸이', '손무기', '손방패', '갑옷', '각반', '장갑'] , 
    print : ( delay = 1000 ) => {
    	setTimeout( () => {
            // this는 window 객체를 가리킴 
            console.log( this === window )     // true  
        	console.log( this.eq.join(",") ) 
        } , delay ) 
    } 
}

character.print()
블로그 이미지

나무뚱이

,