티스토리 뷰

Javascript

[Javascript] this 활용

Gentlemanjs 2022. 4. 15. 13:05

this란?

this는 함수에서 나타나는데, this키워드를 사용하면 그 함수를 호출한 주체(객체)를 가리키게 된다. 쉽게 말해서 '누가 이 함수를 불렀느냐'가 된다.

const myObject = {
    printThis: function() {
        console.log(this);
    }
}

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

myObject.printThis(); // {printThis: ƒ}
printThis(); // Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

위 코드를 살펴보면, this를 콘솔에 출력하는 printThis라는 함수가 두 개 선언되어 있다. 첫 번째는 myObject의 메서드로 선언되어있고 두 번째는 그냥 일반 함수인데, 아랫부분에 두 함수를 실행한 결과를 살펴보면, 메서드로 실행된 함수의 this는 해당 함수를 호출한 주체, 즉 myObject 객체가 출력되고, 두 번째의 경우에는 window 객체가 출력이 되었다.

this의 활용

this는 이렇게 메서드로 활용될 때, 해당 객체의 프로퍼티들을 다양하게 활용할 수 있도록 해준다.

const user = {
    name: 'bigtop',    
    sayHi: function () {
        const msg = `안녕하세요 저는 ${this.name}입니다.`;
        console.log(msg);
    },
}

user.sayHi(); // 안녕하세요 저는 bigtop입니다.
 
댓글
© 2018 webstoryboy