call, bind, apply의 this binding

2023. 4. 19. 16:25·NOTE

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를 바인드 할 수 없다. 

'NOTE' 카테고리의 다른 글

node.js, npm, npx  (0) 2023.04.19
함수와 메소드 차이  (0) 2023.04.19
한글, 영문 폰트 다르게 적용하기  (0) 2023.04.17
자바스크립트 sort()로직  (0) 2023.04.15
매개변수, 인자, 인수  (0) 2023.04.05
'NOTE' 카테고리의 다른 글
  • node.js, npm, npx
  • 함수와 메소드 차이
  • 한글, 영문 폰트 다르게 적용하기
  • 자바스크립트 sort()로직
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • 분류 전체보기 (73)
      • TECH (22)
      • NOTE (40)
      • DAILY (7)
      • javascript (1)
      • 알고리즘 (0)
  • 블로그 메뉴

    • 홈
    • TECH
    • NOTE
    • DAILY
  • 링크

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바