자바스크립트

[JavaScript] this 키워드

코딩하는둥이 2025. 2. 28. 16:45

메소드에서는 this는 해당 객체를 가르킵니다.

const audio = {
    title : 'a',
    play (){
        console.log('play', this);
        
    }
}

audio.play();
audio.stop = function() {
    console.log('stop this', this0);
    
}

audio.stop();

 

 

 

 

함수에서는 this는 widndow 객체를 가르킵니다.

function playAudio(){
    console.log(this);
}
playAudio();

 

생성자 함수에서는 this는  객체를 가르킵니다.

function Audio(title){
    this.title = title;
    console.log(this);
}
const audio = new Audio('a')

 

 

 

화살표 함수에서는 this는  항상 상위스코프의 this를 가르킵니다. => Lexical this

const audio = {
    title: 'audio',
    categories: ['1', '2', '3'],
    displayCategories() {
        this.categories.forEach(category => {
            console.log(this);
            console.log(category);
        });
    }
}

audio.displayCategories();