22장 this

seo0·2023년 3월 24일
0

JavaScript

목록 보기
22/26
post-thumbnail

this 키워드

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.

//전역에서 this
console.log(this);  //window

function add(num){
  //함수 내부에서 tihis
  console.log(this);  //window
  return num + num;
}
add(2);

const person = {
  name: 'kim',
  getName() {
    //객체에서 this
    console.log(this);  //window
    return this.name;
  }
};
console.log(person.getName());  //kim

function Person(name) {
  //생성자 함수 내부에서 this
  this.name = name;
  console.log(this);  //Person {name: Window}
}
const me = new Person(this);

strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩 된다. 일반 함수 내부에서 this를 사용할 필요가 없기 때문이다.




함수 호출 방식과 this 바인딩

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

함수의 상위 스코프를 결정하는 방식인 렉시컬 스코프는 함수의 정의가 평가되어 함수 객체가 생성되는 시점에 상위 스코프를 결정하지만 this 바인딩은 함수 호출 시점에 결정되기 때문에 this 바인딩이 동적으로 결정된다.


함수의 호출 방식

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

일반 함수 호출

기본적으로 this에는 전역 객체가 바인딩 된다. 전역 함수 또는 중첩 함수를 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩 된다. 하지만 this는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수이므로 객체를 생성하지 않는 일반 함수에서 this는 의미가 없다.

//중첩함수 내 this
function outer() {
  console.log('outer: ', this);  //outer:  Window
  function inner() {
    console.log('inner: ', this);  //inner:  Window
  }
  inner();
}
outer();

//메서드의 중첩함수 내 this
var age = 1;
const person = {
  age: 24,
  outer() {
    console.log("outer's this: ", this);  //outer's this:  {age: 24, outer: ƒ}
    console.log("outer's this.age: ", this.age);  //outer's this.age:  24
    
    function inner() {
      console.log("inner's this: ", this);  //inner's this:  Window
      console.log("inner's this.age: ", this.age);  //inner's this.age:  1
    }
    inner();
  }
};

person.outer();

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

//콜백함수 내 this
var age = 1;
const person = {
  age: 24,
  foo() {
    console.log("foo's this: ", this);  //foo's this:  {age: 24, foo: ƒ}
    setTimeout(function() {
      console.log("callback's this: ", this);  //callback's this:  Window
      console.log("callback's this.age: ", this.age);  //callback's this.age:  1
    }, 500);
  }
};

person.foo();

this 바인딩을 일치시키기 위한 방법

  • this 바인딩을 변수에 할당한다.
const person = {
  name: 'kim',
  foo() {
    const self = this;
    console.log(this);  //{name: 'kim', foo: ƒ}
    function inner(){
      console.log(self);  //{name: 'kim', foo: ƒ}
      console.log(self.name);  //kim
    }
    inner();
  }
};

person.foo();
  • 화살표 함수를 사용한다.(화살표 함수 내부의 this는 상위 스코프의 this를 가리킨다.)
const person = {
  name: 'kim',
  foo() {
    console.log(this);  //{name: 'kim', foo: ƒ}
    const inner = () => {
      console.log(this.name);  //kim
    }
    inner();
  }
};

person.foo();
  • apply, call, bind 메서드를 사용한다.
const person = {
  name: 'kim',
  foo() {
    setTimeout(function () {
      console.log(this.name);  //kim
    }.bind(this), 500);
  }
};

person.foo();

메서드 호출

메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다.

const person = {
  name: 'kim',
  getName(){
    console.log(this.name);
  }
};

const person2 = {
   name: 'park',
};

person2.getName = person.getName;

person.getName();  //kim
person2.getName();  //park

생성자 함수 호출

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

function Person(name) {
  this.name = name;
  this.getName = function () {
    console.log(this.name);
  };
}

const person = new Person('kim');
const person2 = new Person('park');

person.getName();  //kim
person2.getName();  //park

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

apply/call/bind는 Function.prototype의 메서드이기 때문에 모든 함수가 프로토타입 체인의 상속을 통해 사용할 수 있다.

apply와 call 메서드의 본질적인 기능은 함수를 호출하는 것이다. 두 메서드는 인수를 전달하는 방식에만 차이가 있을 뿐 동일하게 동작한다.

apply & call

  • apply: 인수를 배열로 묶어 전달한다.
  • call: 인수를 쉼표로 구분한 리스트 형식으로 전달한다.
function thisBinding(){
  console.log(arguments);
  console.log(this);
}

const thisArg = {name: 'kim'};

thisBinding.apply(thisArg, [1, 2 , 3]);
//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//{name: 'kim'}
thisBinding.call(thisArg, 1, 2 , 3);
//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//{name: 'kim'}

arguments 객체와 같은 유사 배열 객체에 배열 메서드는 사용할 수 없지만 apply나 call 메서드를 사용하면 배열 메서드를 사용할 수 있다.

function thisBinding(){
  console.log(arguments);  //Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
  
  const arr = Array.prototype.slice.call(arguments);
    console.log(arr);  //(3) [1, 2, 3]
    return arr;
}

thisBinding(1,2,3);  //(3) [1, 2, 3]

bind

bind 메서드는 apply나 call 메서드와 달리 함수를 호출하지 않는다. 하지만 첫번째 인수로 전달한 값으로 this 바인딩이 교체된 함수를 새롭게 생성해 반환한다.

function thisBinding(){
  console.log(arguments);
  console.log(this);
}

const thisArg = {name: 'kim'};

//bind 메서드는 함수를 호출하지 않기 때문에 명시적으로 호출해야한다.
thisBinding.bind(thisArg);  //Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
thisBinding.bind(thisArg)();  //{name: 'kim'}








📔출처
위키북스 - 모던 자바스크립트 Deep Dive
https://wikibook.co.kr/mjs/

0개의 댓글