this의 의미 6개 총정리

this의 의미 6개 총정리

여기서는 this의 유효범위(scope)를 확인하는것이 포인트 입니다.

01. this (일반(전역)함수에서 this를 사용하는 경우)

<script>
    console.log(this);
    
    function guntion () {
        console.log(this);    
    };
    guntion();
</script>
// 결과)
window
window

02. this (오브젝트 내 함수(메소드)에서 사용하는 경우)

const 오브젝트 = {
    data: 'SO',
    methods : function(){
        naming : function() {
            console.log(this); //여기서의 this는 naming를 가지고 있는 methods를 뜻함
        } 
    }
}

오브젝트.함수();
// 결과)
 
{
 methods : function(){
        naming : function() {
            console.log(this); //여기서의 this는 naming를 가지고 있는 methods를 뜻함
        } 
}

03. this (arrow function에서 사용하는 경우)

내부의 this값을 변화시키지 않음 (외부 this값 그대로 재사용가능)!

const objects = {
    data: {
        mag : [
            {
                id:1,
                msg: 'Hello JS'
            },
            {
                id:2,
                msg: 'Hello JS2'
            },
            {
                id:3,
                msg: 'Hello JS3'
            }
        ]
    },
    methods(){
        console.log(this);  // 여기서의 this는 objects를 가리킵니다. 
        this.data.mag.forEach(element => {
            console.log(this);    //여기서의 this는 내부의 this값을 변화시키지 않음 (외부 objects를 그대로 가리킵니다.!)
            console.log(element); 
        });
    }
}
// 결과)
window

04. this (01번과 02번은 같은 이야기인 이유(window의 비밀) )

01번과 02번은 똑같은 계념 입니다.

-------------------01.----------------
console.log(this);                // window
    
function guntion () {
    console.log(this);            // window
};
-------------------02.----------------
const 오브젝트 = {
    data: 'SO',
    methods : function(){
        naming : function() {
            console.log(this);     //여기서의 this는 naming를 가지고 있는 methods를 뜻함
        } 
    }
}

05. this (constructor(생성자)에서 this 사용하는 경우)

const 객체 = {}

function 공장() {
    this.이름 = 'kim'  //여기서의 this는 새로 생성되는 오브젝트 (instance)를 뜻한다.
}

const 오브젝트 = new 공장();
console.log(오브젝트)
// 결과)
공장 {이름: "kim"}

06. this (event listener 내에서 사용하는 경우)

document.querySelector('.btn').addEventListener('click', function(e){
    console.log(this);            //.btn를 뜻합니다.
    console.log(e.currentTarget); //.btn를 뜻합니다.
});

Last updated