this 키워드를 호출하면 자신을 호출한 객체에 바인드(bind)되는데, 바인드란 메서드와 객체를 묶어놓는 것을 말합니다.

함수 밖에서나 함수 안에서 this 를 사용하면 전역 객체(window)에 바인드되는 반면, 객체나 생성자 함수 내에서는 자신을 호출한 객체에 바인드됩니다.

<script>
  // 함수 밖에서 호출하면 window 에 바인드되고,
  document.write( this + "<br/>");
  // [object Window]

  // 함수 안에서 호출헤도 window 에 바인드됩니다.
  function bind() {
    document.write( this );
  }
  bind(); // [object Window]
</script>

예시처럼 winndow 는 곧 this 라는 사실입니다.

<script>
 var obj = function() {}

 // 아래 예시로 동일한 결과를 얻을 수 있습니다.
 document.write( window.obj );
 document.write( this.obj );
 document.write( obj );



 document.write( this );
 // 결과: [object Window]

 document.write( window );
 // 결과: [object Window]


 // this 는 곧 window 이고, 전역 객체입니다.
 document.write( this == window );
 // 결과: true
</script>

하지만 객체에서 this 키워드를 사용하면 window 가 아닌 자신을 호출한 객체에 바인드된 것을 확인할 수 있습니다.

<script>
  var imName = {
    name: '하보니',
    bind: function() {
      document.write( this == imName );
    },
    wind: function() {
      document.write( this == window );
    }
  };


 // 여기서 this 는 window 가 아니라
 // imName 입니다.
 imName.bind(); // 결과: true

 imName.wind(); // 결과: false
</script>

<script>
  var imName = {
    name: '하보니',
    age: 20,
    job: ['백수', '취준생'],
    bind: function() {
      document.write('안녕 ' + this.name + ' 반가워요!');
      document.write('<br/> 나이는 ' + this.age + ' 이고,');
      document.write('<br/> 직업은 ' + this.job[0] + ' 입니다.');
  }
};


// 여기서 this 는 window 가 아니라 imName 입니다.
imName.bind(); 
// 안녕 하보니 반가워요!
// 나이는 20 이고,
// 직업은 백수 입니다.
</script>

이렇게 this 키워드로 객체의 속성으로 함수를 호출하면 함수 안에서 어떤 객체가 그 함수를 호출하였는지 확인할 수 있습니다.

<script>
function changeName(name) {
  this.name = name;
}
var obj = {
  name: "하보니",
  setName: changeName,
  bind: function(){
    document.write( this == obj );
  }
};

// 이름을 변경하기 전...
document.write( obj.name ); 
// 결과: 하보니


// 여기서 this 는 obj 입니다.
// 이름을 아이유로 변경합니다.
obj.setName("아이유");
document.write( obj.name ); 
// 결과: 아이유


// 여기서 this 는 obj 입니다.
obj.bind(); // true
</script>

obj 객체의 이름이 "하보니"였던 것을 "아이유"로 바뀐 것을 확인할 수 있습니다.

0 댓글