자바스크립트에서 this는 함수를 호출하는 맥락을 의미한다.
별코딩 강의에서는 this를 하나의 객체로 본다면 한마디로 "호출한 놈" 이라고 한다.
호출한 놈이 없다면, window객체가 this다.
전역스코프에서도 window 객체가 this다.
strict mode에서는 호출한 놈이 없을 경우, 기본값이 window가 아닌 undefined가 된다.
- 대부분의 경우, this의 값은 함수를 생성하거나, this를 선언할 때 결정되는 게 아니라, 함수를 호출할 때 결정된다.
- 화살표 함수 안의 this는 선언될 때 결정된다. 이 경우에는 this가 그 함수 안에 있으니까 this는 그 함수겠지~ 이렇게 생각해도 된다.
const car ={
name:'Kia',
getName: function(){
console.log("car getName")
}
}
car.getName()
//이렇게 하면 {name:"Kia", getName: f} 이렇게 car 객체 그 자체가 출력됨.
let person = {
fullname: '짐코딩',
age: 20,
printThis: function(){
console.log(this); //{fullname: '짐코딩', age: 20, printThis: f}
console.log(this === person); //true
console.log(this.fullname); //짐코딩
console.log(this.age); //20
},
};
let printThis = person.printThis;
printThis(); //this가 윈도우 전역객체가 된다. 호출할 때 앞에 호출한 놈이 없기 때문
ES5부터는 bind라는 메서드로 this를 임의로 지정할 수 있다.
function printThis() {
console.log(this); //default this => window
}
printThis(); // window 나옴
let person1 = {
name: '홍길동',
};
let person2 = {
name: '김길동',
};
let printThis1 = This.bind(person1);
printThis1(); //{name:홍길동}나옴.
setTimeout(function(){
alert("hello");
}, 3000);
참고 자료: 자바스크립트 this란 무엇인가? | 웹 개발 입문자들을 위한 this 강좌! (youtube.com)
자바스크립트 this 알아보기 (youtube.com)
개발자 면접 단골질문 자바스크립트 this (youtube.com)
'WEB > Javascript' 카테고리의 다른 글
[JS] promise~ (0) | 2024.05.27 |
---|---|
[JS] console.dir과 console.log의 차이 (0) | 2024.05.21 |
JS dom 조작하기 (0) | 2024.04.09 |
JS 동기와 비동기 (0) | 2024.04.09 |
JS 변수와 함수 선언하기 (0) | 2024.04.02 |