JavaScript의 함수는 호출될 때 매개변수로 전달되는 인자 외에 arguments 객체와 this
를 암묵적으로 전달받는데 이 때 함수 호출 방식에 의해 this
에 바인딩할 어떤 객체가 동적으로 결정된다.
다른 프로그래밍 언어와 달리 this
에 바인딩되는 객체가 한 가지가 아니라 해당 함수 호출 방식에 따라 달라진다는 점에서 차이가 있다.
함수를 호출하는 방식은 다양하다.
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
전역 객체(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 메소드를 제공하고 있다.
함수가 객체의 프로퍼티 값이면 메소드로서 호출된다. 이때 메소드 내부의 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());
JavaScript의 생성자 함수는 다른 객체 지향 언어의 생성자 함수와는 달리 그 형식이 정해져 있는 것이 아니라 기존 함수에 new
연산자를 붙여서 호출하면 해당 함수는 행성자 함수로서 동작한다.
new
연산자와 함께 생성자 함수를 호출하며 다음과 같은 순서로 동작한다.
생성자 함수의 코드가 실행되기 전 빈 객체가 생성된다. 이 빈 객체가 생성자 함수가 새로 생성하는 객체가 되는데 생성자 함수 내부에서 사용되는 this
는 바로 이 빈 객체를 가리킨다.
생성된 빈 객체에 this를 사용하여 동적으로 프로퍼티나 메소드를 생성할 수 있다. this는 새로 생성된 객체를 가리키므로 this를 통해 생성한 프로퍼티와 메소드는 새로 생성된 객체에 추가된다.
function Person(name) {
// ① 생성자 함수 코드 실행 전
this.name = "anne"; // ② 동적 프로퍼티 생성
// ③ 생성된 함수 반환
}
var me = new Person("anne");
console.log(me.name);
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);
JavaScript 엔진의 암묵적 this
바인딩 이외에 this
를 특정 객체에 명시적으로 바인딩하는 방법도 제공된다. 이것을 가능하게 하는 것이 Function.prototype.apply
, Function.prototype.call
메소드이다.
func.apply(thisArg, [argsArray])
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.bind
는 Function.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