TIL 93 l this part2

YB.J·2022년 1월 10일
0

자바스크립트

목록 보기
2/3
post-thumbnail

this part2. 함수 호출 방법 4가지에 따른 this binding에 대해 알아보자

상황에 따른 this binding : 함수호출 part

일반 함수 호출
메서드 호출
생성자 함수 호출
Function.prototype.apply/call/bind 메서드에 의한 간접 호출


바인딩이란?

bind : 결속시키다, 묶다

예를 들어서,

a라는 객체가 있고, b객체에 test()라는 메서드가 있습니다.
b.test()라고 실행되는게 보통이지만 이것을 마치 a객체에서 실행되게 ( a.test() 와 같은 효과 )하는 경우를 메서드와 객체를 묶어놓는다고 표현합니다.

이것을 바인딩이라고 합니다.

출처: https://uxicode.tistory.com/entry/바인딩이란 [세줄코딩]

(1) 일반함수 호출

case 1

기본적으로 this에는 전역객체가 바인딩된다.
전역함수, 중첩함수를 일반함수로 호출하는 경우 함수 내부의 this에는 전역 객체가 바인딩.


 function sharon () {
    console.log(this);
  }

sharon(); // window


 function sharon () {
    console.log(this);
     function bro () {
       console.log(this);
     }
   bro();
  }

sharon(); // window, window

case 2

arrow function : 화살표 함수같은 경우 함수의 호출방식과는 상관없이 자신이 선언된 함수 범위에서 this를 정의한다.


const sharon = {
  name: "SharonJee",
  getName: function () {
    console.log(this.name);
    },
  arrow: () => {
    console.log(this.name)
  }
};

sharon.getName(); 
sharon.arrow();

case 3

'use strict'을 사용할 때 : this는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수이기 때문에 객체를 생성하지 않는 일반 함수에서 this는 의미가 없다. 따라서 아래와 같은 'strict mode'가 적용된 일반 함수 내부의 this에는 undefieded가 바인딩된다.


function sharon() {
  'use strict';
  
 console.log(this); // undefinded
  function bro() {
    console.log(this) // undefinded
  }
  bro()
}

sharon();

profile
♪(^∇^*) 워-후!!(^∀^*)ノシ

0개의 댓글