[JavaScript] 함수 호출 방식과 this 바인딩 💬

혜혜·2024년 11월 2일
1

JavaScript

목록 보기
3/9
post-thumbnail

💡 다 까먹어버린 JavaScript에서의 this 바인딩 개념을 복습해 보자. JavaScript의 this는 객체 지향 언어에서 쓰던 this에 찌든 나에게 긴장감을 주는 헷갈리는 개념이다 😵‍💫 한번 호되게 혼나보러 가자...👊

💡 핵심

📌 JavaScript에서의 this는 함수를 호출할 때, 함수가 어떻게 호출되었는지에 따라 바인딩할 객체가 동적으로 결정된다!!

그렇다면 함수가 어떻게 호출되었는지는 또 뭘까?
대표적인 함수 호출 방식에는 다음의 4가지가 있다.

  1. 그냥 함수 호출
  2. 메소드 호출
  3. 생성자 함수 호출
  4. apply/call/bind 호출
var foo = function () {
  console.dir(this);
};

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

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

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

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

(출처: 하단 참고 자료에 기재)

한눈에 보자면 위와 같다.
이제 각각의 경우에 this가 어떤 값으로 바인딩되는지를 자세히 살펴보자!

1. 함수 호출

그냥 함수 호출일 때 this에 어떤 값이 바인딩되는지를 알아보기 전에, 전역 객체(Global Object) 개념에 대해 알 필요가 있다.

전역 객체(Global Object)란?
: 모든 객체의 유일한 최상위 객체

일반적으로 브라우저에서는 window, 서버 사이드(Node.js)에서는 global 객체를 의미한다!

var ga = 'Global variable';

console.log(ga);
console.log(window.ga);

function foo() {
  console.log('invoked!');
}
window.foo();
  • 전역 객체전역 스코프(Global Scope)를 갖는 전역 변수(Global Variable)를 프로퍼티로 소유함
  • 글로벌 영역에 선언한 함수는, 전역 객체의 프로퍼티로 접근할 수 있는 전역 변수의 메소드
function foo() {
  console.log("foo's this: ",  this);  // window
  function bar() {
    console.log("bar's this: ", this); // window
  }
  bar();
}
foo();
  • 기본적으로 this는 전역 객체에 바인딩됨
    ① '내부 함수'의 경우에도 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 bar() {
      console.log("bar's this: ",  this); // window
      console.log("bar's this.value: ", this.value); // 1
    }
    bar();
  }
};

obj.foo();

② '메소드의 내부 함수'일 경우에도, this는 전역 객체에 바인딩됨

var value = 1;

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

obj.foo();

③ '콜백 함수'의 경우에도, 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();

→ 즉, 내부 함수면, 일반 함수, 메소드, 콜백 함수 어디에서 선언되었든 관계없이 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();

  • foo 안에서의 this는 단순 메소드 안이므로 'obj'를 가리킴
  • 그러나 foo 메소드의 내부 함수인 bar에서는 this가 '전역 객체'를 가리킨다!
  • 여기서도 개발자가 기대한대로 'obj'를 가리키게 하고 싶다면, that 변수를 생성하여 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 bar(a, b) {
      console.log("bar's this: ",  this); // obj
      console.log("bar's this.value: ", this.value); // 100
      console.log("bar's arguments: ", arguments);
    }
    bar.apply(obj, [1, 2]);
    bar.call(obj, 1, 2);
    bar.bind(obj)(1, 2);
  }
};

obj.foo();
  • 이외에도 this를 명시적으로 바인딩할 수 있는 apply, call, bind 메소드가 존재함
  • apply : 첫 번째 인자로 this로 설정할 객체를 받고, 두 번째 인자로 인수 배열을 받음
  • call : 첫 번째 인자로 this로 설정할 객체를 받고, 두 번째 인자부터 인수로 넣을 값들을 차례로 받음
  • bind : this로 설정할 객체를 받아 새로운 함수 반환
    → 셋 다 비슷한 역할을 함

2. 메소드 호출

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

var obj2 = {
  name: 'Kim'
}

obj2.sayName = obj1.sayName;

obj1.sayName(); // Lee
obj2.sayName(); // Kim
  • 함수가 객체의 프로퍼티 값이면, '메소드'로서 호출
  • 이때 메소드 내부의 this해당 메소드를 소유(호출)한 객체에 바인딩

요런 식

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

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

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

Person.prototype.name = 'Kim';
console.log(Person.prototype.getName()); // Kim
  • Prototype 객체도 메소드 가짐
  • Prototype 객체 메소드 내부에서 사용된 this도, 일반 메소드 방식과 동일하게 해당 메소드를 호출한 객체에 바인딩

요런 식

3. 생성자 함수 호출

  • 자바스크립트 생성자 함수는 객체를 생성하는 역할
  • 자바 같은 언어와는 다르게 형식이 정해져 있진 X
  • 기존 함수에 new 연산자를 붙여서 호출하면, 해당 함수가 그냥 생성자 함수로 동작하는 것!
  • 생성자 함수가 아닌 그냥 일반 함수에 new 연산자를 붙여 호출하면 생성자 함수처럼 동작할 수 있음
  • 그래서 일반적으로는 생성자 함수명은 '대문자'로 시작하게 해서 혼란 방지
// 생성자 함수
function Person(name) {
  this.name = name;
}

var me = new Person('Lee');
console.log(me); // Person {name: "Lee"}

// new 연산자와 함께 생성자 함수를 호출하지 않으면 생성자 함수로 동작하지 않는다.
var you = Person('Kim');
console.log(you); // undefined
  • new 연산자와 함께 생성자 함수를 호출하면, 그냥 일반 함수나 메소드를 호출할 때와는 다르게 동작함

⭐ 생성자 함수 동작 방식

1. 빈 객체 생성 및 this 바인딩

  • 생성자 함수 코드가 실행되기 전, '빈' 객체 생성 (생성자 함수가 생성하는 객체임)
  • 이후 생성자 함수 내에서 사용되는 this는 이 빈 객체를 가리킴
  • 이 빈 객체는 생성자 함수의 prototype이라는 프로퍼티가 가리키는 객체를, 자신의 프로토타입 객체로 설정함

2. this를 통한 프로퍼티 생성

  • 생성된 빈 객체에 this를 사용하여 동적으로 프로퍼티나 메소드 생성 가능
  • this는 '새로 생성된 객체'를 가리키므로, this를 통해 생성한 프로퍼티와 메소드는 새로 생성된 객체에 추가됨

3. 생성된 객체 반환

  • 반환문이 없는 경우, this에 바인딩된 새로 생성한 객체가 반환됨 (명시적으로 this 반환해도 결과는 같음)
  • 반환문이 this가 아닌 다른 객체를 명시적으로 반환하는 경우, this가 아닌 명시한 해당 객체가 반환됨 (이때 this를 반환하지 않는 함수는 생성자 함수로서의 역할을 수행하지 못하긴 함.)
function Person(name) {
  // 생성자 함수 코드 실행 전 -------- 1
  this.name = name;  // --------- 2
  // 생성된 함수 반환 -------------- 3
}

var me = new Person('Lee');
console.log(me.name);

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

// 객체 리터럴 방식
var foo = {
  name: 'foo',
  gender: 'male'
}

console.dir(foo);

// 생성자 함수 방식
function Person(name, gender) {
  this.name = name;
  this.gender = gender;
}

var me  = new Person('Lee', 'male');
console.dir(me);

var you = new Person('Kim', 'female');
console.dir(you);

✅ 차이는 프로토타입 객체([[Prototype]])에 있다!

  • 객체 리터럴 방식 : 생성된 객체의 프로토타입 객체는 Object.prototype
  • 생성자 함수 방식 : 생성된 객체의 프로토타입 객체는 Person.prototype

⭐ 생성자 함수에 new 연산자를 붙이지 않고 호출할 경우

  • 일반 함수생성자 함수에 특별한 형식적 차이는 없고, 함수에 new 연산자를 붙여서 호출하면 그냥 해당 함수는 생성자 함수로 동작함
  • But, 생성자 함수를 new 없이 호출하거나 일반 함수에 new를 붙여 호출하면 오류가 발생할 수는 있음
    this 바인딩 방식이 다르기 때문에!
  • 일반 함수를 호출하면 this는 '전역 객체'에 바인딩되지만,
    new 연산자와 함께 생성자 함수를 호출하면 this는 생성자 함수가 암묵적으로 생성한 '빈 객체'에 바인딩됨
function Person(name) {
  // new없이 호출하는 경우, 전역객체에 name 프로퍼티를 추가
  this.name = name;
};

// 일반 함수로서 호출되었기 때문에 객체를 암묵적으로 생성하여 반환하지 않는다.
// 일반 함수의 this는 전역객체를 가리킨다.
var me = Person('Lee');

console.log(me); // undefined
console.log(window.name); // Lee
// Scope-Safe Constructor Pattern
function A(arg) {
  // 생성자 함수가 new 연산자와 함께 호출되면 함수의 선두에서 빈객체를 생성하고 this에 바인딩한다.

  /*
  this가 호출된 함수(arguments.callee, 본 예제의 경우 A)의 인스턴스가 아니면 new 연산자를 사용하지 않은 것이므로 이 경우 new와 함께 생성자 함수를 호출하여 인스턴스를 반환한다.
  arguments.callee는 호출된 함수의 이름을 나타낸다. 이 예제의 경우 A로 표기하여도 문제없이 동작하지만 특정함수의 이름과 의존성을 없애기 위해서 arguments.callee를 사용하는 것이 좋다.
  */
  if (!(this instanceof arguments.callee)) {
    return new arguments.callee(arg);
  }

  // 프로퍼티 생성과 값의 할당
  this.value = arg ? arg : 0;
}

var a = new A(100);
var b = A(10);

console.log(a.value);
console.log(b.value);
  • this 인스턴스 생성자 함수 식별자가 false면, new 연산자와 함께 해당 함수를 재귀 호출하여 반드시 생성자 함수를 호출할 수 있게끔 하는 패턴
  • calleearguments 객체의 프로퍼티로서 함수 바디 내에서 현재 실행 중인 함수를 참조할 때 사용 (즉, 함수 바디 내에서 현재 실행 중인 함수의 '이름'을 반환함)

4. apply/call/bind 호출

  • this에 바인딩될 객체는 함수 호출 패턴에 의해 결정 → 자바스크립트 엔진이 수행하는 것
  • 이러한 암묵적 this 바인딩 외에, this를 특정 객체에 명시적으로 바인딩하는 방법도 제공됨
    → 이걸 가능하게 하는 게 Function.prototype.apply, Function.prototype.call
func.apply(thisArg, [argsArray])

// thisArg: 함수 내부의 this에 바인딩할 객체
// argsArray: 함수에 전달할 argument의 배열
  • apply() 메소드를 호출하는 주체는 함수
var Person = function (name) {
  this.name = name;
};

var foo = {};

// apply 메소드는 생성자함수 Person을 호출한다. 이때 this에 객체 foo를 바인딩한다.
Person.apply(foo, ['name']);

console.log(foo); // { name: 'name' }
  • 빈 객체 fooapply() 메소드를 첫 번째 매개변수에,
    argument의 배열을 두 번째 매개변수에 전달하면서 Person 함수 호출
  • 이때 Person 함수의 thisfoo 객체
  • Person 함수는 thisname 프로퍼티에 매개변수 'name'에 할당된 인수를 할당 → this에 바인딩된 foo 객체에는 name 프로퍼티가 없으므로 name 프로퍼티가 동적 추가되고 값이 할당됨
function convertArgsToArray() {
  console.log(arguments);

  // arguments 객체를 배열로 변환
  // slice: 배열의 특정 부분에 대한 복사본을 생성한다.
  var arr = Array.prototype.slice.apply(arguments); // arguments.slice
  // var arr = [].slice.apply(arguments);

  console.log(arr);
  return arr;
}

convertArgsToArray(1, 2, 3);
  • apply() 메소드의 대표적인 용도는, arguments 객체와 같은 '유사 배열 객체'에 배열 메소드를 사용하고 싶은데 사용할 수 없기 때문에, 이를 가능하게 해 주기 위해 주로 사용함
  • 위 코드에서 Array.prototype.slice.apply(arguments)는, "Array.prototype.slice() 메소드를 호출하라. 단, thisarguments 객체로 바인딩하라!"는 의미가 됨
    → 즉, Array.prototype.slice() 메소드를 arguments 객체 자신의 메소드인 것처럼 arguments.slice() 같은 형태로 호출하라는 것

요런 식

Person.apply(foo, [1, 2, 3]);

Person.call(foo, 1, 2, 3);
  • call() 메소드는 apply()와 기능은 같지만, 인자 넘겨주는 형식만 다름
function Person(name) {
  this.name = name;
}

Person.prototype.doSomething = function(callback) {
  if(typeof callback == 'function') {
    // --------- 1
    callback();
  }
};

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

var p = new Person('Lee');
p.doSomething(foo);  // undefined
  • apply()call()콜백 함수의 this를 위해서 사용되기도 함
  • 일단 '1' 시점에서 thisPerson 객체를 가리킴
  • 하지만 '2' 시점에서는 전역 객체 window를 가리킨다! (내부 함수니까)
  • 콜백함수를 호출하는 외부 함수 내부의 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('Lee');
p.doSomething(foo);  // 'Lee'
  • 따라서 콜백함수 내부의 this를 콜백함수를 호출하는 함수 내부의 this와 일치시켜 줘야 하는 번거로움이 발생
function Person(name) {
  this.name = name;
}

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

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

var p = new Person('Lee');
p.doSomething(foo);  // 'Lee'
  • Function.prototype.bind를 사용하는 방법
  • 이 함수는 인자로 전달한 this가 바인딩된 새로운 함수 리턴
  • 그래서 명시적으로 함수 호출이 필요함

💡 참고 자료

profile
쉽게만살아가면재미없어빙고

0개의 댓글

관련 채용 정보