[22장] this

ssu00·2022년 1월 24일
0

22.1 this 키워드

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

2) this는 자바스크립트 엔진에 의해 암묵적으로 생성되며, 코드 어디서든 참조할 수 있다. 함수를 호출하면 arguments 객체와 this가 암묵적으로 함수 내부에 전달된다.

3) this가 가리키는 값, 즉 this 바인딩함수 호출 방식에 따라 동적으로 결정된다.


4) **객체 리터럴의 메서드** 내부에서의 this는 **메서드를 호출한 객체**를 가리킨다.

const circle = {
radius: 5,
getDiameter(){
return 2 * this.radius;
} //this는 circle
};


5) **생성자 함수** 내부의 this는 **생성자 함수가 생성할 인스턴스**를 가리킨다. 

function Circle(radius){
this.radius = radius;
} //this는 생성자 함수가 생성할 인스턴스
Circle.prototype.getDiameter = function(){
return 2 * this.radius;
}; //this는 생성자 함수가 생성할 인스턴스
const circle = new Circle(5);


6) **전역**에서 this는 전역 객체 **window**를 가리킨다.

<br/>

22.2 함수 호출 방식과 this 바인딩

1) lexical scope함수 객체가 생성되는 시점에 상위 스코프를 결정하지만, this 바인딩함수 호출 시점에 결정된다.

2) 일반 함수 호출
기본적으로 this에는 전역 객체가 바인딩된다. 하지만 strict mode에서는 this에 undefined가 바인딩된다.

function foo () {
  console.log("foo's this: ", this); //strict mode면 undefined, 아니면 window
  function bar() {
    console.log("bar's this: ", this); //strict mode면 undefined, 아니면 window
  }
  bar();
}
foo();

콜백 함수메서드 내에서 정의한 중첩 함수라고 하더라도 일반 함수로 호출되면 내부의 this에는 전역 객체가 바인딩된다.

var value = 1;
const obj = {
  value: 100,
  foo() {
    console.log("foo's this and this.value: ", this, this.value); //{value: 100, foo: f}, 100
    
    //일반 함수로 호출된 콜백 함수
    setTimeout(function (){
      console.log("callback's this: ", this, this.value); //window 1
    }, 100);
    
    //일반 함수로 호출된 중첩 함수
    function bar() { 
      console.log("bar's this and this.value: ", this, this.value); //window 1
    }
    bar();
  }
};
obj.foo();

중첩 함수나 콜백 함수는 외부 함수를 돕는 헬퍼 함수의 역할을 하는데, 이때 외부 함수인 메서드와 this가 일치하지 않는다는 것은 문제가 된다. 메서드 내부의 중첩 함수, 콜백 함수의 this 바인딩메서드의 this 바인딩일치시키기 위한 방법은 다음과 같다.

var value = 1;
const obj = {
  value: 100,
  foo() {
    const that = this; //this바인딩을 that에 할당
    
    //콜백 함수 내부에서는 this 대신 that을 참조
    setTimeout(function () {
      console.log(that.value); //100
    },100);
  }
};

obj.foo();

이외에도 Function.prototype.apply, Function.prototype.call, Function.prototype.bind를 사용하면 this를 명시적으로 바인딩할 수 있다.

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

const person = {
  name: 'Lee',
  getName() {
    return this.name;
  }
};
//메서드 getName을 호출한 객체가 person이므로, person.getName()은 Lee
console.log(person.getName());

위의 예제에서 getName() 메서드를 풀어보면, 다음과 같다.

getName: function() { 
  return this.name;
}

즉, 메서드는 프로퍼티(getName)에 바인딩된 함수이다. getName 프로퍼티가 가리키는 함수 객체는 person 객체에 포함된 것이 아니라 독립적으로 존재하는 별도의 객체이다.

따라서 getName 메서드는 다른 객체의 메서드가 될 수도 있고, 일반 함수로 호출될 수도 있다.

const anotherPerson = {
  name: 'Kim'
};

//다른 객체의 메서드로 할당
anotherPerson.getName = person.getName;
console.log(anotherPerson.getName()); //Kim

//일반 함수로 호출
const getName = person.getName;
console.log(getName()); //'' (window.name과 같으므로)

프로토타입 메서드 내부에서 사용된 this도 일반 메서드와 마찬가지로 해당 메서드를 호출한 객체에 바인딩된다.

function Person(name) { 
  this.name = name;
}
Person.prototype.getName = function() { 
  return this.name;
};
const me = new Person('Lee');
console.log(me.getName()); //'Lee'
Person.prototype.name = 'Kim';
console.log(Person.prototype.getName()); //'Kim'

4) 생성자 함수 호출
생성자 함수는 객체(인스턴스)를 생성하는 함수이다. 생성자 함수 내부의 this에는 생성자 함수가 미래에 생성할 인스턴스가 바인딩된다.

function Circle(radius){
  this.radius = radius;
  this.getDiameter = function() { 
    return 2 * this.radius;
  };
}
const circle1 = new Circle(5);
const circle2 = new Circle(10);
console.log(circle1.getDiameter(),circle2.getDiameter()); //10 20

생성자 함수를 new 연산자 없이 호출하면 일반 함수로 동작한다는 점에 유의해야 한다.

5) Function.prototype.apply/call/bind 메서드에 의한 간접 호출
apply, call, bind 메서드는 Function.prototype의 메서드이다. 따라서 모든 함수가 상속받아 사용할 수 있다.

우선 applycall 메서드의 사용법은 다음과 같다.

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

applycall 메서드는 함수(getThisBinding)를 호출하면서 첫 번째 인수로 전달한 특정 객체(thisArg)를 호출한 함수(getThisBinding)의 this에 바인딩한다.

function getThisBinding() { 
  console.log(arguments);
  return this;
}
const thisArg = {a: 1};
console.log(getThisBinding()); //window

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

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

apply와 call 메서드는 호출할 함수에 인수를 전달하는 방식만 다를 뿐 동일하게 동작한다.

bind 메서드는 함수를 호출하지 않고 this로 사용할 객체만 전달한다. 메서드의 this와 메서드 내부의 중첩 함수, 콜백 함수의 this가 불일치하는 문제를 해결할 때 유용하게 사용된다.

const person = {
  name: 'Lee',
  foo(callback) {
    setTimeout(callback, 100);
  }
};
person.foo(function() {
  console.log(`Hi! My name is ${this.name}.`);  
  //Hi! My name is .
  //콜백 함수가 일반 함수로서 호출됐으므로 this는 window이다. 
});

위 예제에서 person.foo 내부의 this와 콜백 함수 내부의 this는 상이하다. 이는 bind 메서드를 사용해 해결할 수 있다.

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

person.foo(function() {
  console.log(`Hi! My name is ${this.name}.`);
  //Hi! My name is Lee.
});

0개의 댓글