본문 바로가기
Programming/자바스크립트

[자바스크립트] this - 개념

by 코딩하는 랄로 2023. 11. 3.
728x90

this란?

프로그래밍을 공부하다보면, this라는 키워드를 많이 마주하게 치게 된다. this는 영어로 이것이라는 의미로 프로그래밍 언어에서는 this를 호출한 '이것'을 의미한다. 그렇기 때문에 this는 누가 호출했냐에 따라 어떤 객체에 바인딩 되는지가 정해지는 것이다.

 

여기서 바인딩이라는 말은 bind, 묶다라는 의미를 지닌 용어로 this의 객체를 바인딩한다는 것은 this의 객체를 묶는 것을 의미한다. 간단하게 tihs의 객체가 할당되는 것이다. 위에서도 언급하였듯이 this는 어디에서 호출했냐에 따라 바인딩 되는 객체가 달라진다. 이번 포스팅을 통해서 상황에 따른 this의 바인딩에 대해서 알아보자.

 

 

 

단독으로 사용한 this

일반적으로 this는 자신을 호출한 객체를 바인딩한다고 하였는데 그렇다면 this를 그냥 사용할 경우 어떤 객체가 바인딩 될까? 이를 알아보기 위해 브라우저 콘솔 창에 this를 출력해보겠다.

 

위의 결과처럼, 바로 this를 쓴다면 window 객체가 바인딩 되는 것을 알 수 있다.

 

 

 

일반함수에서의 this (생성자, 메소드 제외)

함수에서의 this는 함수가 어떤 함수냐에 따라 this에 바인딩 되는 객체가 달라진다. 생성자 함수와 객체의 메소드를 제외한 일반 함수에서의 this는 함수를 호출하는 전역 객체, 즉 window 객체를 바인딩한다.

 

내부 함수 또는 콜백 함수 또한 호출하는 주체는 window 객체이기 때문에 window 객체가 바인딩 된다. 

 

 

 

생성자 함수의 this

생성자 함수에서의 this는 생성자 함수가 생성하는 객체가 바인딩된다. 그렇기 때문에 생성자 함수내에서 해당 객체의 변수를 초기화할 때 this 키워드를 사용하여 해당 객체의 변수에 접근할 수 있는 것이다.

// 생성자 함수에서의 this는 생성된 객체가 바인딩
function Person(name, age) {
    this.name = name;
    this.age = age;
}

const person1 = new Person('kim', 26)
const person2 = new Person('lee', 26)

console.log(person1.name) //kim 
console.log(person2.name) //lee

 

 

그렇기 때문에 같은 생성자를 통해 생성된 객체여도 독립된 객체로서 각자의 프로퍼티를 가질 수 있는 것이다. 이는 자바스크립트의 class 생성자에서의 constructor에도 마찬가지이다. ( 두 개의 문법이 자바스크립트 엔진 내부에서는 똑같이 동작하기 때문에...)

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

const person1 = new Person('kim', 26)
const person2 = new Person('lee', 26)

console.log(person1.name) //kim 
console.log(person2.name) //lee

 

 

 

 

메소드의 this

메소드에서의 this도 생성자 함수와 마찬가지로 해당 메소드를 호출한 객체를 바인딩한다.

// 객체의 메소드
const person = {
    name : 'kim',
    age : 26,
    printInfo : function() {
        return this.name + " " + this.age;
    }
}

console.log(person.printInfo())  //kim 26


// 클래스의 메소드
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    printInfo() {
        return this.name + " " + this.age;
    }
}

const person2 = new Person('lee', 24);
console.log(person2.printInfo()); //lee 24

 

일반 함수를 메소드의 함수로 사용하여도 윈도우 객체가 바인딩 되는 것이 아닌 호출한 객체가 바인딩 된다.

let name = 'window'

function printName() {
    console.log(this.name); 
}

printName(); //undefined => window 객체의 name 프로퍼티가 없으므로

const thisObj = {
    name : 'kim',
    printInfo : printName,
};

thisObj.printInfo();  //kim => 호출한 객체 thisObj가 바인딩

 

 

 

이벤트 핸들러의 this

이벤트 핸들러에서 this는 이벤트를 받는 HTML 요소를 가리킨다.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div style="width: 100px; height: 100px; border: 1px solid black;">
    this
  </div>
</body>
  <script>
    const thisEvent = document.querySelector('div');
    thisEvent.addEventListener('click', function() {
      console.log(this);
    });
  </script>
</html>

 

위의 코드를 통해 나온 div 박스를 click 해보면 브라우저의 콘솔 창에 아래와 같이 click 이벤트를 통해 등록된 콜백 함수를 호출한 div 요소가 tihs에 바인딩 되는 것을 볼 수 있다.

 

 

 

화살표 함수의 this

화살표 함수의 this는 해당 함수를 호출한 스코프의 상위 스코프를 가지는 객체를 바인딩 한다. 아래는 일반 함수를 사용하였을 경우 setTimeout 함수안의 this가 윈도우 객체를 바인딩하기 때문에 원치 않는 결과를 내는 코드이다.

// 일반적인 함수의 this
// 전역 객체 => window를 가리킴
var Person = function (name, age) {
    this.name = name;
    this.age = age;
    this.printInfo = function () { //객체의 메소드
        console.log(this); // Person {name: "kim", age: 26} <= this는 객체

        setTimeout(function () { // 콜백함수
            console.log(this); // Window가 바인딩
            console.log(this.name + ' ' + this.age);
        }, 100);
    };
};
var person = new Person('kim', 26);

person.printInfo(); //undefined undefined

 

 

이 때에, 해당 함수를 콜백함수로 변경해준다면 원하는 결과가 잘 출력되는 것을 볼 수 있다.

var Person = function (name, age) {
    this.name = name;
    this.age = age;
    this.printInfo = function () { //객체의 메소드
        console.log(this); // Person {name: "kim", age: 26} <= this는 객체

        setTimeout(() => { // 화살표 함수
            console.log(this); // Person {name: "kim", age: 26} <= 상위 스코프의 객체 Person이 바인딩
            console.log(this.name + ' ' + this.age);
        }, 100);
    };
};
var person = new Person('Kim', 26);
person.printInfo(); //Nana Kim

 

 

화살표 함수의 this는 this의 바인딩 중 이해하기가 쉽지 않은 개념이다. 화살표 함수의 this 바인딩에 대해서 더 자세히 알고 싶다면 아래의 블로그를 참고하기 바란다.

https://codingralro.tistory.com/entry/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-Arrow-Function

 

[자바스크립트] Arrow Function

화살표 함수 (Arrow Function) 화살표 함수는 ES6에서 도입된 문법으로 function 키워드 대신 화살표(=> , arrow)를 사용하여 함수를 선언할 수 있다. 화살표 함수가 분명 함수를 선언하는데에 편리한 방법

codingralro.tistory.com

 

728x90