call, bind, apply의 this binding

2023. 4. 19. 16:25·javascript

this

아무것도 없는 상태에서 this는 글로벌객체인 window를 가르킨다. 

 

자바스크립트 this가 결정되는 시점은
선언시점이 아닌 누가 실행하는지에 따라서 결정된다. 

 

consoleA를 실행할때 testObj가 실행하고 있으므로

this는 testObj를 가르킨다. 

const testObj = {
    a: '1234',
    consoleA: function() {
        console.log(this.a);
    }
}

testObj.consoleA(); //1234

 

변수에 메소드를 할당해서 실행하는경우

실행할 때 this는 testObj가 아닌 window를 가르킨다. 

const testObj = {
    a: '1234',
    consoleA: function() {
        console.log(this.a);
    }
}

const test = testObj.consoleA;
test(); //undefinded

 

할당해서 실행하는경우 this가 실종되는 이슈 해결법

this를 고정해주는 방법으로 call, apply, bind를 사용할 수 있다. 

 

call, apply

call, apply는 첫번째 인자로 지정할 bind를 넣어주고, 두번째 인자로 함수에 필요한 파라미터를 넣어준다.

const testobj = {
    name: 'aa'
};

function sayTest(city) {
    console.log(`${city}에 사는 ${this.name}`)
};

sayTest.call(testobj, 'seoul'); // seoul에 사는 aa

 

여기서 call, apply의 차이점은 apply는 두번째 인자로 배열을 받는 것 이다.

const testobj = {
    name: 'bb'
};

function sayTest(city) {
    console.log(`${city}에 사는 ${this.name}`)
};

sayTest.apply(testobj, ['youngin']); //youngin에 사는 bb

 

bind

call, apply와 동일하게 this를 지정하는 메소드이다. 

다른점은 함수를 바로 실행하지 않는다는 점이다. 

const testobj = {
    name: 'bb'
};

function sayTest(city, age) {
    console.log(`${city}에 사는 ${this.name}은 ${age}세 입니다.`)
};

const testSayObj = sayTest.bind(testobj, 'youngin', '13');
testSayObj(); // youngin에 사는 bb은 13세 입니다.

 

화살표함수에서는 call, apply, bind메소드를 이용해 this를 바인드 할 수 없다. 

'javascript' 카테고리의 다른 글

배열의 두 요소 순서를 변경할 때  (0) 2023.05.05
Array.prototype.reduce()  (0) 2023.04.20
자바스크립트 sort()로직  (0) 2023.04.15
fetch() error 처리하기  (0) 2023.03.17
parseInt(), Number() 의 차이  (0) 2023.03.02
'javascript' 카테고리의 다른 글
  • 배열의 두 요소 순서를 변경할 때
  • Array.prototype.reduce()
  • 자바스크립트 sort()로직
  • fetch() error 처리하기
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • TECH (82)
      • Next.js (8)
      • React (25)
      • Vite (1)
      • javascript (17)
      • CSS (6)
      • CS (10)
      • AWS (0)
      • Jest (1)
      • CI|CD (0)
      • 알고리즘 (8)
      • Tools (1)
      • Tips (5)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      redux
      react state management
      Array.sort()
      배열요소순서
      styled-components
      git배포
      함수와 메서드차이
      JavaScript
      React
      app-router
      커머스프로젝트
      TypeScript
      타입스크립트
      call signatures
      reat-head
      global-style
      nextjs
      서버컴포넌트
      theme-provider
      웹브라우저구성
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    ssund
    call, bind, apply의 this binding
    상단으로

    티스토리툴바