this

mandoo·2022년 11월 2일
0

JavaScript

목록 보기
6/7

JavaScript의 함수는 호출될 때 매개변수로 전달되는 인자 외에 arguments 객체와 this를 암묵적으로 전달받는데 이 때 함수 호출 방식에 의해 this에 바인딩할 어떤 객체가 동적으로 결정된다.
다른 프로그래밍 언어와 달리 this에 바인딩되는 객체가 한 가지가 아니라 해당 함수 호출 방식에 따라 달라진다는 점에서 차이가 있다.

함수를 호출하는 방식은 다양하다.

  • 함수 호출
  • 메소드 호출
  • 생성자 함수 호출
  • apply, call, bind 호출
var foo = function () {
  console.dir(this);
};

// 1. 함수 호출
foo(); // window

// 2. 메소드 호출
var obj = { foo: foo };
obj.foo(); // object

// 3. 생성자 함수 호출
var instance = new foo(); // foo

// 4. apply/call/bind 호출
var bar = { name: 'bar' };
foo.call(bar);   // object
foo.apply(bar);  // object
foo.bind(bar)(); // object

1. 함수 호출

전역 객체(Global Object)는 모든 객체의 유일한 최상위 객체를 의미하며 일반적으로 Browser-side에서는 window, Server-side(Node.js)에서는 global 객체를 의미한다.
전역 객체는 전역 스코프(Global scope)를 갖는 전역 변수(Global variable)을 프로퍼티로 갖는다. 전역에 선언한 함수는 전역 객체의 프로퍼티로 접근할 수 있는 전역 변수의 메소드이다.

기본적으로 this는 전역 객체에 바인딩된다. 전역 함수는 물론이고 심지어 내부 함수의 경우도 this는 외부 함수가 아닌 전역 객체에 바인딩된다.

function outer() {
  console.log("outer's this: ",  this);  // outer's this: window
  function inner() {
    console.log("inner's this: ", this); // inner's this: window
  }
  inner();
}
outer();

또한 메소드의 내부함수일 경우에도 this는 전역 객체에 바인딩된다.

var value = 1;

var obj = {
  value: 100,
  foo: function() {
    console.log("foo's this: ",  this);  // obj
    console.log("foo's this.value: ",  this.value); // 100
    function inner() {
      console.log("inner's this: ",  this); // window
      console.log("inner's this.value: ", this.value); // 1
    }
    inner();
  }
};

obj.foo();

콜백 함수의 경우에도 this는 전역 객체에 바인딩된다.

var value = 1;

var obj = {
  value: 100,
  foo: function() {
    setTimeout(function() {
      console.log("callback's this: ",  this);  // callback's this: window
    });
  }
};

obj.foo();

내부 함수는 일반 함수, 메소드, 콜백 함수 어디에서 선언되었든 관게없이 this는 전역 객체를 바인딩한다.
내부 함수의 this가 전역 객체를 참조하는 것을 회피하는 방법은 아래 코드와 같다.

var value = 1;

var obj = {
  value: 100,
  foo: function() {
    var that = this;  // Workaround : this === obj

    console.log("foo's this: ",  this);  // obj
    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

      console.log("bar's that: ",  that); // obj
      console.log("bar's that.value: ", that.value); // 100
    }
    bar();
  }
};

obj.foo();

위 방법 이외에도 JavaScript는 this를 명시적으로 바인딩할 수 있는 apply, call, bind 메소드를 제공하고 있다.

2. 메소드 호출

함수가 객체의 프로퍼티 값이면 메소드로서 호출된다. 이때 메소드 내부의 this는 해당 메소드를 소유한 객체, 즉 해당 메소드를 호출한 객체에 바인딩된다.

var person1 = {
  name: 'anne',
  sayName: function() {
    console.log(this.name);
  }
}

var person2 = {
  name: 'gilbert'
}

obj2.sayName = obj1.sayName;

obj1.sayName();
obj2.sayName();

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

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

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

var me = new Person('anne');
console.log(me.getName());

Person.prototype.name = 'gilbert';
console.log(Person.prototype.getName());

3. 생성자 함수 호출

JavaScript의 생성자 함수는 다른 객체 지향 언어의 생성자 함수와는 달리 그 형식이 정해져 있는 것이 아니라 기존 함수에 new 연산자를 붙여서 호출하면 해당 함수는 행성자 함수로서 동작한다.

1) 생성자 함수 동작 방식

new 연산자와 함께 생성자 함수를 호출하며 다음과 같은 순서로 동작한다.

① 빈 객체 생성 및 this 바인딩

생성자 함수의 코드가 실행되기 전 빈 객체가 생성된다. 이 빈 객체가 생성자 함수가 새로 생성하는 객체가 되는데 생성자 함수 내부에서 사용되는 this는 바로 이 빈 객체를 가리킨다.

② this를 통한 프로퍼티 생성

생성된 빈 객체에 this를 사용하여 동적으로 프로퍼티나 메소드를 생성할 수 있다. this는 새로 생성된 객체를 가리키므로 this를 통해 생성한 프로퍼티와 메소드는 새로 생성된 객체에 추가된다.

③ 생성된 객체 반환

  • 반환문이 없는 경우: this에 바인딩된 새로 생성한 객체가 반환된다. 명시적으로 this를 반환하여도 결과는 같다.
  • 반환문이 this가 아닌 다른 객체를 명시적으로 반환하는 경우, this가 아닌 해당 객체가 반환된다. 이때 this를 반환하지 않은 함수는 생성자 함수로서의 역할을 수행하지 못한다. 따라서 생성자 함수는 반환문을 명시적으로 사용하지 않는다.
function Person(name) {
  //  ① 생성자 함수 코드 실행 전
  this.name = "anne"; // ② 동적 프로퍼티 생성
  // ③ 생성된 함수 반환
}

var me = new Person("anne");
console.log(me.name);

2) 객체 리터럴 방식과 생성자 함수 방식의 차이

var obj = {
  name: "diana";
  gender: "female";
}

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

var me = new Person("anne", "female");
console.dir(me);
  • 객체 리터럴 방식의 경우, 생성된 객체의 프로토타입 객체는 Object.prototype이다.
  • 생성자 함수 방식의 경우, 생성된 객체의 프로토타입 객체는 Person.prototype이다.

4) apply, call, bind 호출

JavaScript 엔진의 암묵적 this 바인딩 이외에 this를 특정 객체에 명시적으로 바인딩하는 방법도 제공된다. 이것을 가능하게 하는 것이 Function.prototype.apply, Function.prototype.call 메소드이다.

func.apply(thisArg, [argsArray])
  • thisArg: 함수 내부의 this에 바인딩할 객체
  • argsArray: 함수에 전달할 인자(argument)의 배열

apply() 메소드를 호출하는 주체는 함수이며 apply()메소드는 this를 특정 객체에 바인딩할 뿐 본질적인 기능은 함수 호출이라는 점을 주의해야 한다.

var Person = function (name, gender) {
  this.name = name;
  this.gender = gender
};

var obj = {};

Person.apply(obj, ["anne", "female"]);
console.log(obj); { name: "anne", gender: "female" };

빈 객체 obj를 apply() 메소드의 첫 번째 매개변수에, argument의 배열을 두 번째 매개변수에 전달하면서 Person 함수를 호출하였다. 이때 Person 함수의 this는 obj 객체가 된다. Person 함수는 this의 name 프로퍼티에 매개변수 name에 할당된 인수를 할당하는데 this에 바인딩된 obj 객체에는 name 프로퍼티가 없으므로 name 프로퍼티가 동적 추가되고 값이 할당된다.

call() 메소드의 경우 apply()와 기능은 같지만 apply()가 두 번째 인자에서 배열 형태로 넘긴 것을 각각 하나의 인자로 넘긴다.

Person.apply(obj, ["anne", "female"]);
Person.call(obj, "anne", "female");

apply()와 call() 메소드는 콜백 함수의 this를 위해서 사용되기도 한다.

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

Person.prototype.doSomething = function(callback) {
  if(typeof callback == 'function') {
    // --------- ① 메소드 함수 호출
    callback();
  }
};

function foo() {
  console.log(this.name); // --------- ② 내부 함수 호출
}

var p = new Person('anne');
p.doSomething(foo);  // undefined

①의 시점에서 this는 Person 객체이다. 그러나 2의 시점에서 this는 전역 객체 window를 가리킨다. 콜백함수를 호출하는 외부 함수 내부의 this와 콜백함수 내부의 this가 상이하기 때문에 문맥 상 문제가 발생한다. 따라서 콜백함수 내부의 this를 콜백함수를 호출하는 함수 내부의 this와 일치시켜 주어야 하는 번거로움이 발생한다.

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

Person.prototype.doSomething = function (callback) {
  if (typeof callback == 'function') {
    callback.call(this);
  }
};

function foo() {
  console.log(this.name);
}

var p = new Person('anne');
p.doSomething(foo);  // anne

Function.prototype.bind를 사용하는 방법도 있다. Function.prototype.bind는 함수에 인자로 전달한 this가 바인딩된 새로운 함수를 리턴한다. 즉, Function.prototype.bindFunction.prototype.apply, Function.prototype.call 메소드처럼 함수를 실행하지 않기 때문에 명시적으로 함수를 호출해야 한다.

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

Person.prototype.doSomething = function(callback) {
  if(typeof callback == 'function') {
    // this가 바인딩된 새로운 함수를 호출
    callback.bind(this)();
  }
};

function foo() {
  console.log(this.name);
}

var p = new Person('anne');
p.doSomething(foo);  // anne

4. 참고 문서

poiemaweb: JavaScript 함수 호출 방식에 의해 결정되는 this

profile
매일 조금씩이라도 꾸준히

0개의 댓글