Review - ES6 문법(3)

Verba volant, scripta manent·2021년 1월 28일
0

이제 ES6 문법 마지막편이다.
this에 대해 전체적으로 복습할 것이다.

this란?

자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수를 뜻한다.
함수가 호출되는 방식에 따라 this에 바인딩(식별자와 값을 연결하는 과정)이 동적으로 결정된다.

함수 호출 방식

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

ex)
let foo = function () {
  console.dir(this);
};

위의 코드를 예시로 들도록 하겠다.

1. 일반 함수 호출

foo 함수를 일반적인 방식으로 호출하며 foo 함수 내부의 this는 전역 객체인 window를 가리킨다.

ex)
foo(); // window

2. 메서드 호출

foo 함수를 property 값으로 할당하여 호출하며 foo 함수 내부의 this는 메서드를 호출한 객체 obj를 가리킨다.

ex)
let obj = { foo };
obj.foo(); // obj

3. 생성자 함수 호출

foo 함수를 new 연산자와 함께 생성자 함수로 호출하며 foo 함수 내부의 this는 생성자 함수가 생성한 인스턴스를 가리킨다.

ex)
new foo(); // foo {}

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

foo 함수 내부의 this는 인수에 의해 결정된다.

ex)
let bar = { name: 'bar' };

foo.call(bar); // bar
foo.apply(bar); // bar
foo.bind(bar)(); // bar

this 바인딩

함수 호출 방식에 따라 this 바인딩이 달라진다.

1. 일반 함수 호출

일반 함수로 호출된 모든 함수 내부의 this에는 전역 객체가 바인딩된다.

ex)
function foo() {
  console.log("foo's this: ", this); // window
  function bar() {
    console.log("bar's this: ", this); // window
  }
  bar();
}
foo();

2. 메서드 호출

메서드 내부의 this에는 메서드를 호출한 객체, 즉 메서드를 호출할 때 메서드 이름 앞의 마침표(.) 연산자 앞에 기술한 객체가 바인딩된다.

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

Person.prototype.getName = function() {
  return this.name;
};

let me = new Person('Yeon');

// getName 메서드를 호출한 객체는 me이다.
console.log(me.getName()); // Yeon

Person.prototype.name = 'Shin';

// getName 메서드를 호출한 객체는 Person.prototype이다.
console.log(Person.Prototype.getName()); // Shin

3. 생성자 함수 호출

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

ex)
function Circle(radius) {
  this.radius = radius;
  this.getDiameter = function() {
    return 2 * this.radius;
  };
};

// 반지름이 10인 Circle 객체를 생성한다.
let circle1 = new Circle(10);
// 반지름이 20인 Circle 객체를 생성한다.
let circle2 = new Circle(20);

console.log(circle1.getDiameter()); // 20
console.log(circle2.getDiameter()); // 40

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

1. Function.prototype.apply, Function.prototype.call 메서드

this로 사용할 객체와 인수 리스트를 인수로 전달받아 함수로 호출한다.

<Function.prototype.apply 메서드 사용법>
주어진 this 바인딩과 인수 리스트 배열을 사용하여 함수를 호출한다.

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

thisArg : this로 사용할 객체
argsArray : 함수에게 전달할 인수 리스트의 배열 또는 유사 배열 객체
호출된 함수의 반환값을 return 한다.

<Function.prototype.call 메서드 사용법>
주어진 this 바인딩과 ,로 구분된 인수 리스트를 사용하여 함수를 호출한다.

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

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

ex)
function getThisBinding() {
  console.log(arguments);
  return this;
}

// this로 사용할 객체
let 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}

2. Function.prototype.bind 메서드

함수를 호출하지 않고 this로 사용할 객체만 전달한다.

ex)
function getThisBinding() {
  return this;
}

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

// bind 메서드는 함수에 this로 사용할 객체를 전달한다.
// bind 메서드는 함수를 호출하지는 않는다.
console.log(getThisBinding.bind(thisArg)); // getThisBinding
// bind 메서드는 함수를 호출하지는 않으므로 명시적으로 호출해야 한다.
console.log(getThisBinding.bind(thisArg)()); // {a: 1}

정리

함수 호출 방식 this 바인딩
일반 함수 호출 전역 객체
메서드 호출 메서드를 호출한 객체
생성자 함수 호출 생성자 함수가 미래에 생성할 인스턴스
Function.prototype.apply/call/bind 메서드에 의한 간접 호출 Function.prototype.apply/call/bind 메서드에 첫번째 인수로 전달한 객체
profile
말은 사라지지만 기록은 남는다

0개의 댓글