[FE] 📚 자바스크립트에서 this란?
🤗 오늘의 위클리 페이퍼는
자바스크립트에 this 키워드에 대한 토픽입니다.
📝 바인딩이란?
함수 또는 메소드를 호출한 대상에 실제 함수를 연결해주는 것을 말합니다.
자바스크립트에서 this 는 어떤 환경에서 사용하는지에 따라 this 에 바인딩되는 객체가 달라집니다.
📗 this란?
자바스크립트의 this 키워드는 함수가 호출되는 방식에 따라 달라지는 특별한 키워드입니다.
this는 기본적으로 함수를 호출한 객체를 참조합니다.
자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수를 말합니다.
자바스크립트에서 this 는 호출방식에 따라서 동적으로 결정됩니다.
1. 글로벌 문맥 (Global Context)
글로벌 문맥에서는 'this'는 전역 객체를 참조합니다.
브라우저에서는 'window' 객체를 참조합니다.
console.log(this === window); // true
Node.js에서는 'global' 객체를 참조합니다.
console.log(this); // 브라우저에서는 window 객체를 출력
2. 함수 문맥 (Function Context)
단순 호출
전역에서 함수를 호출하고 있어 this 는 전역 객체인 window 가 바인딩됩니다.
function returnThis() {
return this;
}
console.log(returnThis() === window); // true
일반 함수 내부에서 'this'는 기본적으로 전역 객체를 참조합니다.
function showThis() {
console.log(this);
}
showThis(); // 브라우저에서는 window 객체를 출력
'use strict';
function showThis() {
console.log(this);
}
showThis(); // undefined
3. 메서드 문맥 (Method Context)
객체의 메서드에서 'this'는 해당 메서드를 소유한 객체를 참조합니다.
함수를 어떤 객체의 메소드로 호출하면 this 의 값은 그 객체가 바인딩됩니다.
const person = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
person.greet(); // "Alice" 출력
함수를 어떤 객체의 메소드로 호출하면 this 의 값은 그 객체가 바인딩됩니다.
function returnThis() {.
return this;
}
const obj = {
name: 'obj',
returnThis: returnThis
};
console.log(obj.returnThis() === obj); // true
4. 생성자 함수 문맥(Constructor Function Context)
함수를 new 키워드와 함께 생성자로 사용하면 this 는 새로 생긴 객체가 됩니다.
function Person(name) {
this.name = name;
}
// new 연산자로 호출한 경우
const obj = new Person('이름');
console.log(obj.name === '이름'); // true
// new 연산자 없이 호출한 경우
const obj2 = Person('윈도우');
console.log(obj2 === undefined); // true
console.log(window.name === '윈도우'); // true
생성자 함수에서 'this'는 새로 생성되는 인스턴스를 참조합니다.
function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice.name); // "Alice" 출력
5. 'call', 'apply', 'bind' 메서드를 사용한 문맥
이 메서드들을 사용하면 'this' 값을 명시적으로 설정할 수 있습니다.
'bind' 새로운 함수를 반환하며, 이 함수의 'this'가 영국적으로 지정됩니다.
위에서 살펴본 것들은 this 로 설정될 객체가 함수 호출 패턴에 의해 결정된 것들입니다.
이렇게 암묵적인 방법 이외에 this 를 특정 객체에 명시적으로 바인딩하는 방법도 있습니다.
obj2 에서 실행하는 returnThis 에 this 로 obj 가 바인딩 된 예시입니다.
function returnThis() {
return this;
}
const obj = { name: 'obj' };
const obj2 = returnThis.bind(obj)();
console.log(obj === obj2); // true
'call', 'apply' 즉시 함수를 호출하면서 'this'를 저장합니다.
function greet() {
console.log(this.name);
}
const person = { name: 'Alice' };
greet.call(person); // "Alice" 출력
greet.apply(person); // "Alice" 출력
const boundGreet = greet.bind(person);
boundGreet(); // "Alice" 출력
6. 화살표 함수(Arrow Function)
일반 함수처럼 호출한 대상에 따라 상대적으로 변하는 것이 아니라, Arrow Function을 감싸는 정적 범위(Lexical Scope)인 선언되기 직전에 유효한 this 를 갖게 됩니다. 아래에 returnThis 가 선언되기 직전에 유효한 this 는 window 객체입니다
const returnThis = () => this;
const obj = {
name:'obj',
returnThis: returnThis,
returnThis2: () => this
};
console.log(obj.returnThis() === window); // true
화살표 함수는 자신만의 'this' 바인딩을 가지지 않으며, 정의된 위치에서 'this'를 상속받습니다.
const person = {
name: 'Alice',
greet: function() {
const inner = () => {
console.log(this.name);
};
inner();
}
};
person.greet(); // "Alice" 출력
이와 같이, 자바스크립트의 this는 함수 호출 방식에 따라 달라지며, 이를 이해하는 것은 자바스크립트에서의 함수와 객체 지향 프로그래밍을 이해하는 데 매우 중요합니다.