💡 다 까먹어버린 JavaScript에서의 this 바인딩 개념을 복습해 보자. JavaScript의 this는 객체 지향 언어에서 쓰던 this에 찌든 나에게 긴장감을 주는 헷갈리는 개념이다 😵💫 한번 호되게 혼나보러 가자...👊
📌 JavaScript에서의
this
는 함수를 호출할 때, 함수가 어떻게 호출되었는지에 따라 바인딩할 객체가 동적으로 결정된다!!
그렇다면 함수가 어떻게 호출되었는지는 또 뭘까?
대표적인 함수 호출 방식에는 다음의 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
가 어떤 값으로 바인딩되는지를 자세히 살펴보자!
그냥 함수 호출일 때 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
가 '전역 객체'를 가리킨다!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
로 설정할 객체를 받아 새로운 함수 반환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
this
도, 일반 메소드 방식과 동일하게 해당 메소드를 호출한 객체에 바인딩요런 식
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
연산자를 붙여서 호출하면 그냥 해당 함수는 생성자 함수로 동작함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
// 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);
false
면, new
연산자와 함께 해당 함수를 재귀 호출하여 반드시 생성자 함수를 호출할 수 있게끔 하는 패턴callee
는 arguments
객체의 프로퍼티로서 함수 바디 내에서 현재 실행 중인 함수를 참조할 때 사용 (즉, 함수 바디 내에서 현재 실행 중인 함수의 '이름'을 반환함)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' }
foo
를 apply()
메소드를 첫 번째 매개변수에,argument
의 배열을 두 번째 매개변수에 전달하면서 Person
함수 호출Person
함수의 this
는 foo
객체Person
함수는 this
의 name
프로퍼티에 매개변수 '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()
메소드를 호출하라. 단, this
는 arguments
객체로 바인딩하라!"는 의미가 됨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
를 위해서 사용되기도 함this
는 Person
객체를 가리킴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
가 바인딩된 새로운 함수 리턴