this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
//전역에서 this
console.log(this); //window
function add(num){
//함수 내부에서 tihis
console.log(this); //window
return num + num;
}
add(2);
const person = {
name: 'kim',
getName() {
//객체에서 this
console.log(this); //window
return this.name;
}
};
console.log(person.getName()); //kim
function Person(name) {
//생성자 함수 내부에서 this
this.name = name;
console.log(this); //Person {name: Window}
}
const me = new Person(this);
strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩 된다. 일반 함수 내부에서 this를 사용할 필요가 없기 때문이다.
자바스크립트의 this는 함수가 호출되는 방식에 따라 this에 바인됭 될 값, 즉 this 바인딩이 동적으로 결정된다.
함수의 상위 스코프를 결정하는 방식인 렉시컬 스코프는 함수의 정의가 평가되어 함수 객체가 생성되는 시점에 상위 스코프를 결정하지만 this 바인딩은 함수 호출 시점에 결정되기 때문에 this 바인딩이 동적으로 결정된다.
함수의 호출 방식
기본적으로 this에는 전역 객체가 바인딩 된다. 전역 함수 또는 중첩 함수를 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩 된다. 하지만 this는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수이므로 객체를 생성하지 않는 일반 함수에서 this는 의미가 없다.
//중첩함수 내 this
function outer() {
console.log('outer: ', this); //outer: Window
function inner() {
console.log('inner: ', this); //inner: Window
}
inner();
}
outer();
//메서드의 중첩함수 내 this
var age = 1;
const person = {
age: 24,
outer() {
console.log("outer's this: ", this); //outer's this: {age: 24, outer: ƒ}
console.log("outer's this.age: ", this.age); //outer's this.age: 24
function inner() {
console.log("inner's this: ", this); //inner's this: Window
console.log("inner's this.age: ", this.age); //inner's this.age: 1
}
inner();
}
};
person.outer();
콜백 함수가 일반함수로 호출된다면 콜백 함수의 내부에 위치한 this에도 전역 객체가 바인딩된다. 즉, 일반함수로 호출된 모든 함수(중첩함수, 콜백함수 포함) 내부의 this에는 전역 객체가 바인딩된다.
//콜백함수 내 this
var age = 1;
const person = {
age: 24,
foo() {
console.log("foo's this: ", this); //foo's this: {age: 24, foo: ƒ}
setTimeout(function() {
console.log("callback's this: ", this); //callback's this: Window
console.log("callback's this.age: ", this.age); //callback's this.age: 1
}, 500);
}
};
person.foo();
const person = {
name: 'kim',
foo() {
const self = this;
console.log(this); //{name: 'kim', foo: ƒ}
function inner(){
console.log(self); //{name: 'kim', foo: ƒ}
console.log(self.name); //kim
}
inner();
}
};
person.foo();
const person = {
name: 'kim',
foo() {
console.log(this); //{name: 'kim', foo: ƒ}
const inner = () => {
console.log(this.name); //kim
}
inner();
}
};
person.foo();
const person = {
name: 'kim',
foo() {
setTimeout(function () {
console.log(this.name); //kim
}.bind(this), 500);
}
};
person.foo();
메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다.
const person = {
name: 'kim',
getName(){
console.log(this.name);
}
};
const person2 = {
name: 'park',
};
person2.getName = person.getName;
person.getName(); //kim
person2.getName(); //park
생성자 함수 내부의 this에는 생성자 함수가 미래에 생성할 인스턴스가 바인딩된다.
function Person(name) {
this.name = name;
this.getName = function () {
console.log(this.name);
};
}
const person = new Person('kim');
const person2 = new Person('park');
person.getName(); //kim
person2.getName(); //park
apply/call/bind는 Function.prototype의 메서드이기 때문에 모든 함수가 프로토타입 체인의 상속을 통해 사용할 수 있다.
apply와 call 메서드의 본질적인 기능은 함수를 호출하는 것이다. 두 메서드는 인수를 전달하는 방식에만 차이가 있을 뿐 동일하게 동작한다.
function thisBinding(){
console.log(arguments);
console.log(this);
}
const thisArg = {name: 'kim'};
thisBinding.apply(thisArg, [1, 2 , 3]);
//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//{name: 'kim'}
thisBinding.call(thisArg, 1, 2 , 3);
//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//{name: 'kim'}
arguments 객체와 같은 유사 배열 객체에 배열 메서드는 사용할 수 없지만 apply나 call 메서드를 사용하면 배열 메서드를 사용할 수 있다.
function thisBinding(){
console.log(arguments); //Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
const arr = Array.prototype.slice.call(arguments);
console.log(arr); //(3) [1, 2, 3]
return arr;
}
thisBinding(1,2,3); //(3) [1, 2, 3]
bind 메서드는 apply나 call 메서드와 달리 함수를 호출하지 않는다. 하지만 첫번째 인수로 전달한 값으로 this 바인딩이 교체된 함수를 새롭게 생성해 반환한다.
function thisBinding(){
console.log(arguments);
console.log(this);
}
const thisArg = {name: 'kim'};
//bind 메서드는 함수를 호출하지 않기 때문에 명시적으로 호출해야한다.
thisBinding.bind(thisArg); //Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
thisBinding.bind(thisArg)(); //{name: 'kim'}
📔출처
위키북스 - 모던 자바스크립트 Deep Dive
https://wikibook.co.kr/mjs/