반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

taenyLog

[JavaScript] Arrow Function and 'this' 본문

Web

[JavaScript] Arrow Function and 'this'

taenyLog 2023. 9. 26. 09:17
반응형
const person = {
    firstName : 'Taeny',
    lastName : 'Kim',
    fullName : function(){
        `${this.firstName} ${this.lastName}`
    }
}

여기서 this가 person을 가르키니까 Taeny Kim의 값을 얻을 수 있다.

 

 

const person = {
    firstName : 'Taeny',
    lastName : 'Kim',
    fullName : function() => {
        `${this.firstName} ${this.lastName}`
    }
}

화살표 함수 안에 있는 this 키워드는 함수가 만든 범위를 가리킨다.  즉, 윈도우 객체를 가리킨다.

 

 

const person = {
    firstName : 'Taeny',
    lastName : 'Kim',
    fullName : function() => {
        `${this.firstName} ${this.lastName}`
    }
    shoutName: function(){
        setTimeout(function(){
        	console.log(this.fullName())
        }, 3000
    }
}

결과는 TypeError: this.fullName is not a function 가 뜬다. 

setTimeout은 윈도우 객체의 메서드이다.  윈도우 객체를 내포하고 있어서 보이지 않는다.

 

 

const person = {
    firstName : 'Taeny',
    lastName : 'Kim',
    fullName : function() => {
        `${this.firstName} ${this.lastName}`
    }
    shoutName: function(){
        setTimeout(function() => {
        	console.log(this.fullName())
        }, 3000
    }
}

화살표 함수로 변경시 this키워드가 person 객체를 가리켰다. 이름 전체를 호출했음..

 

화살표 함수 안에 있는 this 키워드는 함수가 만든 범위에 상속되는 this 키워드 값과 같다.

 

일반 함수와 달리 화살표 함수에서 this 키워드는 다르게 작동한다.

 

반응형

'Web' 카테고리의 다른 글

[JavaScript] SPREAD (1) 배열 펼치기  (0) 2023.09.26
[JavaScript] Default Params(old way VS new way)  (0) 2023.09.26
[JavaScript] Reduce  (0) 2023.09.26
[JavaScript] some / every exercise  (0) 2023.09.26
[JavaScript] some and every method  (0) 2023.09.23