FrontEnd/ES&JS 문법

[Javascript] this 정리

기은P 2022. 10. 20. 13:24
반응형

1. this의 정의 

자바스크립트의 this현재 실행 문맥이라고 합니다. 여기서 현재 실행 문맥이라는 건 호출자를 뜻하는데, 호출자는 크게 세 가지로 나뉘어집니다.

 

  • 객체의 메소드
  • 함수
  • 생성자 함수

 

만약 this가 나온다면 세 가지 경우 중 하나인 함수호출방식에 따라 누가 호출했는지 보고 this가 어떤 의미를 가지는지를 따져보면 됩니다. 이를 함수 호출 패턴이라고 하며, 자바스크립트의 this 함수 호출 패턴에 따라 this 가 어떤 객체의 this 가 될 지 정해지고, 이것을 this 바인딩이라고 합니다.

 

 

 2. 사용방법

2-1) 객체의 메소드 호출할 때의 this 바인딩

var obj = {
  name: ‘test’
  sayName: function() {
    console.log(this.name);
  }
};
 
var kim = obj;
kim.name = "kim";
kim.sayName(); // "kim"
 
var lee = obj;
lee.name = "lee";
lee.sayName(); // "lee"

위와 같이 함수가 객체의 프로퍼티 값이면, 자신을 호출한 객체에 바인딩이 되며, 메소드로서 호출됩니다.

 

 

 

 

2-2) 함수를 호출할 때의 this 바인딩

기본적으로 this전역 개체(window)에 바인딩 되서 아래 코드처럼 this를 사용하면 전역에 있는 val 변수에 할당된 Hello가 출력됩니다.

var val = "Hello";
 
var func = function() {
  console.log(this.val);
};
func(); // "Hello"
console.log(this.val); // "Hello"
console.log(window.val); //  "Hello"
console.log(this === window); // true

 

 

콜백함수도 마찬가지로 this전역객체에 바인딩 됩니다.

var value = 1;
 
var obj = {
  value: 100,
  foo: function() {
    setTimeout(function() {
      console.log("callback's this: ",  this);  // window
      console.log("callback's this.value: ",  this.value); // 1
    }, 100);
  }
};
 
obj.foo();

 

 

주의할 점은 내부함수는 일반함수, 메소드, 콜백함수, 어디에서 선언되었던 관계없이 this는 전역객체를 바인딩합니다.

이런 구조를 피하는 방법은 아래와 같이 var that = this; 로 초기화해서 사용하면 됩니다.

var value = 1;
 
var obj = {
  value: 100,
  foo: function() {
    var that = this;  // Workaround : this === obj
 
    console.log("foo's this: ",  this);  // obj
    console.log("foo's this.value: ",  this.value); // 100
    function bar() {
      console.log("bar's this: ",  this); // window
      console.log("bar's this.value: ", this.value); // 1
 
      console.log("bar's that: ",  that); // obj
      console.log("bar's that.value: ", that.value); // 100
    }
    bar();
  }
};
 
obj.foo();

 

 

 

2-3) 생성자 함수 호출할 때의 this 바인딩

var Person = function(name) {
  this.name = name;
};
 
var kim = new Person("kim");
console.log(kim.name); //kim
 
var lee = new Person("lee");
console.log(lee.name); //lee

New를 통해 생성자 함수를 생성한 객체에 대해 바인딩이 됩니다.

 

 

 

 

반응형