본문 바로가기

Javascript

[모던 자바스크립트 Deep Dive] 19. this

this 키워드

this : 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수

  • this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드 참조 가능
  • this는 자바스크립트 엔진에 의해 암묵적으로 생성되며 코드 어디서든 참조 가능
  • 함수를 호출하면 arguments 객체와 this 가 암묵적으로 함수 내부에 전달 → arguments 객체와 this 지역변수처럼 사용 가능
  • this 바인딩은 함수 호출 방식에 의해 동적으로 결정

바인딩 : 식별자와 값을 연결하는 과정

자바스크립트의 this 는 함수가 호출되는 방식에 따라 this 에 바인딩될 값, 즉 this 바인딩이 동적으로 결정

// this는 어디서든지 참조 가능
// 전역에서 this 는 전역 객체 window
console.log(this);	// window

function square(number){
 // 일반 함수 내부에서 this 는 전역 객체 window
 console.log(this); // window
 return number * number;
}
square(2);

const person = {
 name : 'Echichi',
 getName(){
  // 메서드 내부에서 this는 메서드를 호출한 객체 
  console.log(this); // {name : 'Echichi', getName : f}
  return this.name;
 }
};

console.log(person.getName()); // Echichi

function Person(name){
 this.name = name;
 // 생성자 함수 내부에서 this는 생성자 함수가 생성할 인스턴스
 console.log(this); // Person {name : 'Echichi'}
}

const me = new Person('Echichi');

this 는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수로 일반적으로 객체의 메서드 또는 생성자 함수 내부에서만 의미

→ 일반 함수 내부에서는 this를 사용할 필요가 없으므로 strict mode에서는 undefined 가 바인딩  

함수 호출 방식과 this 바인딩

this 바인딩 (this에 바인딩될 값) 은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정

렉시컬 스코프와 this 바인딩은 결정 시기가 다르다

: 함수의 상위 스코프를 결정하는 방식인 렉시컬 스코프는 함수 정의가 평가되어 함수 객체가 생성되는 시점에 상위 스코프를 결정하지만 this 바인딩은 함수 호출 시점에 결정

 

함수 호출 방식 

  1. 일반 함수 호출
  2. 메서드 호출
  3. 생성자 함수 호출
  4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

1. 일반 함수 호출

기본적으로 this에는 전역 객체가 바인딩

일반 함수에서의 this 는 의미가 없으므로 strict mode가 적용된 일반 함수 내부의 this 에는 undefined가 바인딩

// var 키워드로 선언한 전역 변수 value 는 전역 객체의 프로퍼티 
var value = 1;

const obj = {
 value : 100;
 foo(){
  console.log(`foo's this : ${this}`);  // {value : 100, foo : f}
  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 
  }
  
  // 메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this 에는 전역 객체 바인딩
  bar();
 }
};

obj.foo();

메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this에는 전역 객체가 바인딩

var value = 1;

const obj = {
  value: 100,
  foo() {
    console.log(`foo's this : ${this}`); // {value : 100, foo : f}
    // 콜백 함수 내부의 this 에는 전역 객체가 바인딩
    setTimeout(function () {
      console.log(`callback's this : ${this}`); // window
      console.log(`callback's this.value : ${this.value}`); // 1
    }, 100);
  },
};

obj.foo();

콜백 함수가 일반 함수로 호출되면 콜백 함수 내부의 this 에도 전역 객체가 바인딩

일반 함수로 호출된 모든 함수(중첩 함수, 콜백 함수 포함) 내부의 this 에는 전역 객체가 바인딩

하지만 메서드 내에서 정의한 중첩 함수, 콜백 함수(보조 함수)같은 외부 함수를 돕는 헬퍼 함수의 this 가 전역 객체를 바인딩 하는 것은 문제

→ 상위 함수에 변수를 선언 및 정의하여 콜백 함수 내부에서 사용

var value = 1;

const obj = {
  value: 100,
  foo() {
    // this 바인딩 (obj)을 변수 that에 할당
    const that = this;

    setTimeout(function () {
     // 콜백 함수 내부에서 this 대신 that 참조
      console.log(that.value); // 100
    }, 100);
  },
};

obj.foo();

 

Function.prototype.apply/call/bind  메서드 사용 

var value = 1;

const obj = {
  value: 100,
  foo() {
    // 콜백 함수에 명시적으로 this 바인딩
    setTimeout(function () {
      console.log(that.value); // 100
    }.bind(this), 100);
  },
};

obj.foo();

 

화살표 함수 사용

var value = 1;

const obj = {
  value: 100,
  foo() {
    // 화살표 함수 내부의 this 는 상위 스코프의 this 를 가리킨다
    setTimeout(()=>console.log(this.value), 100);
  },
};

obj.foo();

 

2. 메서드 호출

메서드를 호출할 때 메서드 이름 앞의 마침표 연산자 앞에 기술한 객체가 바인딩

→ 메서드를 소유한 객체가 아니라 메서드를 호출한 객체에 바인딩

const person = {
  name: "Echichi",
  getName() {
    // 메서드 내부의 this는 메서드를 호출한 객체에 바인딩
    return this.name;
  },
};

console.log(person.getName());  // Echichi

const anotherPerson = {
 name : "Achichi"
};
// getName 메서드를 anotherPerson 객체의 메서드로 할당
anotherPerson.getName = person.getName;

// getName 메서드를 호출한 객체는 anotherPerson
console.log(anotherPerson.getName()); // Achichi

// getName 메서드를 변수에 할당 
const getName = person.getName;

// getName 메서드를 일반 함수로 호출
console.log(getName()); // ''
// 일반 함수로 호출된 getName 함수 내부의 this.name 은 브라우저 환경에서 window.name과 같다
// 브라우저 환경에서 window.name은 브라우저 창의 이름을 나타내는 빌트인 프로퍼티이며 기본값은 '' 이다
// Node.js 환경에서 this.name 은 undefined

person 객체의 getName 프로퍼티가 가르키는 함수 객체는 person 객체에 포함된 것이 아니라 독립적으로 존재하는 별도의 객체

→ 다른 객체의 메서드가 될 수도 있고 일반 변수에 할당하여 일반 함수로 호출 가능

 

프로토타입 메서드 내부에서 사용된 this 도 해당 메서드를 호출한 객체에 바인딩

// 생성자 함수
function Person(name){
 // 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다
 this.name = name;
 this.sayHello = function(){
  return `Hello! I'm ${this.name}`
 };
};

const person1 = new Person("Echichi");
const person2 = new Person("Achichi");

console.log(person1.sayHello());	// Hello! I'm Echichi
console.log(person1.sayHello());	// Hello! I'm Achichi

3. 생성자 함수 호출

생성자 함수 내부의 this에는 생성자 함수가 (미래에) 생성할 인스턴스가 바인딩

function Person(name) {
  this.name = name;
}

// 프로토타입에 getName 메서드 할당
Person.prototype.getName = function () {
  return this.name;
};

const me = new Person("Echichi");

// getName 메서드를 호출한 주체는 me 객체
console.log(me.getName()); // Echichi

Person.prototype.name = "Achichi";

// 이 시점에서 getName 메서드를 호출한 주체는 Person.prototype 객체
console.log(Person.prototype.getName()); // Achichi

 

4. Function.prototype.apply/ call/ bind 메서드에 의한 간접 호출

apply, call, bind 메서드는 Function.prototype 메서드로 모든 함수가 상속받아 사용 가능

// apply 사용법
함수.apply(this로 사용할 객체, 호출할 함수의 인수 배열 또는 유사배열객체)

// call 사용법
함수.call(this로 사용할 객체, 호출할 함수의 인수 객체)

// bind 사용법
함수.bind(this로 사용할 객체)

 

4-1. apply/ call

  • apply 와 call 메서드의 본질적인 기능은 함수를 호출하는 것
  • 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 호출한 함수의 this에 바인딩
function getThisBinding(){
 console.log(arguments);
 return this;
}

// this로 사용할 객체
const thisArg = { a : 1 };

// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩
// apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달
console.log(getThisBinding.apply(thisArg, [1,2,3]));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// {a : 1}

// call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달
console.log(getThisBinding.call(thisArg, 1,2,3));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// {a : 1}

 

4-2. bind

  • apply 와 call 메서드와 달리 함수 호출 X
  • 첫 번째 인수로 전달한 값으로 this 바인딩이 교체된 함수를 새롭게 생성하여 반환
  • 메서드의 this 와 중첩함수, 콜백함수의 this 가 불일치하는 문제를 해결하기 위해 유용하게 사용
function getThisBinding(){
 return this;
}

// this 로 사용할 객체
const thisArg = { a : 1 };

// bind 메서드는 첫 번째 인수로 전달한 thisArg로 this 바인딩이 교체된
// getThisBinding 함수를 새롭게 생성해 반환
console.log(getThisBinding.bind(thisArg)); // getThisBinding
// bind 메서드는 함수를 호출하지는 않으므로 명시적으로 호출해야 한다
console.log(getThisBinding.bind(thisArg)()); // { a : 1 }

 

callback 함수 내부의 this 를 외부 함수 내부의 this 와 일치시킬 때 사용

const person = {
  name: "Echichi",
  foo(callback) {
	// bind 메서드로 callback 함수 내부의 this 바인딩을 전달
    setTimeout(callback.bind(this), 100);
  },
};

person.foo(function () {
  console.log(`Hello! I'm ${this.name}`); // Hello! I'm Echichi
});

 

함수 호출 방식 this 바인딩
일반 함수 호출 전역 객체
메서드 호출 메서드를 호출한 객체
생성자 함수 호출 생성자 함수가 (미래에) 생성할 인스턴스
Function.prototype.apply/call/bind 메서드에 의한 간접 호출 Function.prototype.apply/call/bind 메서드에 첫 번째 인수로 전달한 객체