[JavaScript] this / bind

정호·2024년 9월 2일
0

TIL

목록 보기
20/20

this

JavaScript에서의 this는 다른 언어랑 좀 다르다.

어떤 객체를 가르키는 키워드
"this는 함수를 호출한 객체이다"
-> 함수를 호출한 객체가 누구인지만 중요

전역 문맥

전역적인 문맥에서 접근하면 this는 윈도우 객체가 된다.

console.log(this)

함수 내부

function main(){
  console.log(this)
}
main()

"this는 함수를 호출한 객체이다"
1. function으로 함수를 정의하면 함수는 window객체에 등록됨

2. main()호출하면 window객체 불러짐

  • main() === window.main()
  • main함수를 직접적으로 호출한 객체는 window 따라서 함수안에 있는 this값은 윈도우 객체
  • window를 생략하고 main함수를 호출해도 똑같이 윈도우 객체안에 있는 main함수를 호출한거임

Object

const object = {
  name:'jungo',
  main: function () {
    console.log(this);
  },
};
object.main();
// {name:'jungo',main:f}
const main2 = object.main;
main2();

함수안에 있는 this는 함수를 호출한 객체가 된다.

  • object라는 객체가 main을 호출 (object의 메서드로 main호출)
    따라서thisobject가 된다.
  • 객체의 다른 속성에 접근할때 유용
    -this.name // jungo

main2

main2는 window 출력

  • main2함수를 호출한 객체는 object가 아니고 전역적으로 호출된 함수

main함수를 먼저 정의하고 객체의 구성원으로 포함시킨 경우

function main(){
  console.log(this)
}

const object = {
  name:'jungo',
  main,
};
object.main();
//{name:'jungo',main:f}

결과 동일

  • 함수가 object 바깥에서 정의되든 안에서 정의되든 main함수를 호출한 객체가 object라면 this는 object

함수의 this값이 궁금하면 .바로 왼쪽객체를 보면된다!


bind

함수에 우리가 원하는 객체를 binding 해준다.
우리가 원하는 객체를 this값으로 설정해주고 싶음

function main(){
  console.log(this)
}

const mainBind = main.bind({name: 'hi'})
mainBind();
  • this값이 window가 아니라 {name: 'hi'}
    이미 bind된걸 또 bind할수는 없음
const object = {
  name:'jungo',
  main: function () {
    console.log(this);
  }.bind({name: '객체'}),
};
object.main();
  • this값이 {name:'객체'}로 바뀐다.
profile
열심히 기록할 예정🙃

0개의 댓글

관련 채용 정보