js에서의 this는??
- 객체를 가리키는 키워드
- 상황에 따라 바뀜
- this는 자신을 포함한 함수를 호출한 객체이다.
- 전역적인 객체에서 this를 가리키면 window 객체가 나옴(엄격모드 'use strict' 와 상관없이 항상 )
- 브라우저 자체의 객체는 window니까 console.log(this)를 했을 때 console의 주체는 window니까 window가 나온겨. window.console.log(this) 라는 뜻
function main(){
console.log(this);
}
main() // 이렇게 호출하는 것은 사실 window.main() 과 같음. 즉 window 객체를 가리키게 됨
// 'use strict' 모드라면 main()을 호출했을때 undefined가 나옴
// 엄격 모드에서는 windoe.main()이라고 호출했을시 this가 윈도우 객체를 가리키게 됨
const obj = {
name:'asd',
main: function () {
console.log(this);
},
};
object.main() // 이럴경우 해당 this를 호출한것은 obj 이므로 this 는 obj를 가리키게 됨
/**
function main() {
console.log(this);
}
const obj = {
name:'asd',
main,
};
object.main() // 이럴경우에도 해당 this를 호출한것은 obj 이므로 this 는 obj를 가리키게 됨
*/
const obj = {
name:'asd',
smallObj :{
name:'sdsd",
main: function () {
console.log(this);
},
}
};
object.smallObj.main() // 이럴경우 해당 this를 직접 호출한것은 smallObj이므로 this는 smallObj를 가리키게 됨
this를 내 입 맛에 맞게 고정시키기 => bind()
- this를 누가 호출하든 상관없이 고정시키고 싶다면 bind 키워드 추가
- bind는 새로운 함수를 호출해주는것 ( 이미 바인드 된 것을 한번 더 바인드 할 수는 없음=>무시당함)
- 첫 인자의 value로는 this 키워드 설정, 이어지는 인자들은 바인드 된 함수의 인수에 제공됨
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
page에서 this를 활용하기
const button = document.getElementById('btn');
button.addEventListner('click',function(){
console.log(this);
});
// 버튼을 클릭하면 콘솔창에는 <button id="btn">버튼</button> 이 뜬다. (html 요소는 요렇게 만들어져 있다고 가정)
// envent.target 은 this와 같다 === 로 if문을 때려보면 true 나옴
화살표 함수와의 차이
- 전통적인 방법 function main(){}
- 호출 방법에 따른 this 변화
- this를 고정하기 위해 bind() 사용
- 화살표 함수 const main = () =>{}
- 더 간결한 함수 선언 문법
- this가 호출에 따라 바뀌지 않음
- this를 외부에서 가져옴
'FrontEnd > JavaScript' 카테고리의 다른 글
[자바스크립트] 이터러블 개념과 FE에서의 사용처 (0) | 2023.06.24 |
---|---|
[자바스크립트] map 메서드와 Map 객체의 차이 (0) | 2023.06.24 |
Axios에 대하여 (vs Fetch) (0) | 2022.12.07 |
JSON Fetch 사용하기 (0) | 2022.12.04 |
JSON 이란? (0) | 2022.12.04 |