JavaScript - this 키워드
this
this는 object를 가리킨다.
어떠한 object를 가리키는지는 호출되는 상황에 따라 다르다.
상황에 따라 this가 가리키는 object
1. 객체의 메소드 안 this -> 객체를 가리킴
2. this 혼자 사용됨 -> 전역 객체를 가리킴
3. 함수 내부에서 this -> 전역 객체를 가리킴
4. 'strict mode'일때 함수 내부 this -> this는 undefined
5. 이벤트 내부에서 this -> 이벤트를 받은 요소(element)
6. call(), apply(), bind() -> this는 어떤 객체든 가리킬 수 있음
하나씩 알아보자
<예시로 사용할 객체>
const person = {
firstName : "John",
lastName : "Doe",
id : 5500,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
1. 객체 메소드 안의 this
객체 메소드 안의 this는 메소드의 객체를 가리킨다.
위 예시에서 fullName 메소드는 person 객체의 메소드이기 때문에 this는 person 객체를 가리킨다.
2. this 혼자 사용됨
this 혼자 사용되는 경우 전역 객체를 가리킨다.
브라우저의 전역 객체는 'Window'
let x = this;
console.log(x)
3. 함수 내부에서 this
함수 내부에서 this는 디폴트로 global object인 'Window'로 바인딩된다.
function sample() {
return this;
}
console.log(sample())
4. 'strict mode'일때 함수 내부 this
자바스크립트 strict mode는 디폴트 바인딩을 허용하지 않습니다.
그러므로 'strict mode'일때 함수 내부 this는 'undefined'
"use strict"
function sample() {
return this;
}
console.log(sample())
5. 이벤트 내부에서 this
이벤트 내부에서 this는 해당 이벤트를 전달받은 HTML 요소를 가리킨다.
HTML
<body>
<button id="btn">Click me</button>
</body>
JS
const btn = document.getElementById('btn');
btn.addEventListener('click', function(e) {
console.log(this);
});
버튼을 클릭하면 이벤트를 전달받은 button element가 콘솔에 출력된다.
6. Explicit Function Binding - call(), apply(), bind()
자바스크립트에는 call(), apply()와 같은 메소드가 이미 정의되어있다.
6.1 call()
인자로 주어지는 객체의 속성을 사용할 수 있다.
6.2 apply()
call 함수와 비슷하나 call 함수가 인자를 ','로 구분하여 받을때 apply 함수는 인자를 배열로 받는다.
6.3 bind()
bind() 함수로 한 객체는 다른 객체의 메소드를 빌릴 수 있다.