하루 기록

22장, this 본문

Book/모던 자바스크립트 Deep Dive

22장, this

떼굴펜 2024. 5. 29. 15:02

: 자기 참조 변수 (자신이 속한 객체를 가리키는 식별자)

 

함수 호출 방식에 의해 동적으로 결정된다.

 

OO에서 this는 ㅁㅁ 이다.
전역에서  전역 객체 window
일반 함수 내부에서 전역 객체 window
메서드 내부에서 매서드 호출한 객체
생성자 함수 내부에서 생성자 함수가 생성할 인스턴스
apply/call/bind 메서드에 의한 간접 호출 메서드에 첫번째 인수로 전달한 객체

 

console.log(this); //window   [전역]

function foo() {
   console.log(this); // window [일반 함수 내부]
}
foo();

const person = {
   name : '떼굴펜',
   getName() {
       console.log(this); // {name : '떼굴펜', getName:f  [메서드 내부]
       return this.name;
   }
}
console.log(person.getName());  // '떼굴펜'

function Person(name) {
    this.name = name;
    console.log(this);  // Person {name : '민수'}    [생성자 함수 내부]
}
const me = new Person('민수');

 

 

apply/call/bind 메서드에 의한 간접 호출

/**
  @param thisArg : this로 사용할 객체
  @param argsArray : 함수에게 전달할 인수 리스트의 배열 or 유사배열 객체
  @return : 호출된 함수의 반환값
*/

Function.prototype.apply(thisArg[, argsArray[)

 

/**
  @param thisArg : this로 사용할 객체
  @param arg1, arg2, ... : 함수에게 전달할 인수 리스트
  @return : 호출된 함수의 반환값
*/

Function.prototype.call(thisArg[, arg1[, arg2[, ... ]]])

 

/**
  @param thisArg : this로 사용할 객체
  @return : 함수
*/

Function.prototype.bind(thisArg)

function getThisBinding() {
   return this;
}
const thisArg = {a:1};

console.log(getThisBinding.bind(thisArg));    // f : getThisBinding
console.log(getThisBinding.bind(thisArg)());  // {a: 1};    bind 메서드는 함수를 호출하지 않으므로 명시적 호출 필요

'Book > 모던 자바스크립트 Deep Dive' 카테고리의 다른 글

23장, 실행 컨텍스트  (0) 2024.05.30
21장, 빌트인 객체  (0) 2024.05.29
20장, _ strict mode  (0) 2024.05.28
19장, 프로토 타입  (0) 2024.05.17
18장, 함수와 일급 객체  (0) 2024.05.09