갈푸라떼
갈푸라떼는 개발중
갈푸라떼
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • CS (0)
      • CSinfo (0)
    • Frontend (15)
      • HTML,CSS (1)
      • Javascript (2)
      • React (0)
      • React Hook (12)
    • Backend (0)
      • Python (0)
      • Node.js (0)
      • php (0)
    • DB (2)
      • MySQL (2)
      • BigQuery (0)
      • Mongodb (0)
    • Study (186)
      • JavaScript (72)
      • JavaScript(Clean code) (50)
      • Node.js (11)
      • HTML,CSS (13)
      • React (30)
      • TypeScript (10)
      • React-Native (0)
    • Error (2)
      • error (2)
    • Git (22)
      • Git (22)
    • Help Coding (4)
      • Useful websites (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github

공지사항

인기 글

태그

  • symbol
  • nodemon
  • 스코프 체인
  • 인터프리터
  • function
  • 실행 컨텍스트
  • 렉시컬 환경
  • Arrow
  • 오버라이딩
  • ECMAScript
  • prototype
  • 싱글스레드
  • this
  • 컴파일러
  • 심볼
  • 함수
  • 정적 레벨
  • 자바스크립트엔진
  • PM2
  • 원시타입
  • 객체타입
  • structure
  • Babel
  • 프로토타입
  • 이터러블
  • class
  • 호이스팅
  • 상속
  • SPREAD
  • 네이밍

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갈푸라떼

갈푸라떼는 개발중

Study/JavaScript

[JavaScript_study] This바인딩

2022. 4. 14. 21:24

* This  (이것)

  • 문맥에 따라 이것(This)가 가리키는 것이 달리짐
  • 생성자 함수 안, 객체 안, 클래스 안에서 this를 사용하였는데 this는 앞으로 만들어질 인스턴스 또는 지금 객체 자기 자신을 가리키는 용도로 사용하였다.
  • 이렇게 this를 사용하면서 나 자신의 instance를 가리키는 것 즉, 특정한 객체와 이 this를 묶어두는 연결된 것을 this바인딩 이라고 한다.
  • C++, C#, JAVA 코드상에서 this 바인딩은 정적으로 결정된다.
    • 한번 instance를 가리키는 this가 결정이 되면 this는 계속 그 instance하나만 정적으로 꾸준히 가리킨다.
  • JS와 TS는 런타임상에서 동적으로 this바인딩이 결정된다.
  • 글로벌 컨텍스트의 this는 무엇을 가리키는가?
    • 브라우저 : window
    • 노드 : 모듈

 

* this 예시 코드

'use strict';

// 모듈값을 설정해주지 않으면 노드상에서는 텅텅빈 모듈이 나온다.
// 모듈을 설정해주면 모듈값이 등록되어 출력된다.
const x = 0;
module.exports.x = x;
console.log(this);
// globalThis를 출력하면 node에서 사용가능한 전역객체가 출력이 된다.
console.log(globalThis);
// globalThis.setTimeout()

// globalThis는 생략이 가능하다 아래의 예시처럼 작성해도 된다.
// setTimeout()

console.clear();

/**
 * 함수 내부에서의 this
 * 엄격모드에서는 undefined
 * 느슨한 모드에서는 globalThis
 */
function fun() {
  console.log(this);
}
fun();

/**
 * 생성자 함수 또는 클래스에서의 this, 앞으로 생성될 인스턴스 자체를 가리킴
 */
function Cat(name) {
  this.name = name;
  this.printName = function () {
    console.log(this.name);
  };
}
const cat1 = new Cat('냐옹');
const cat2 = new Cat('미야옹');
cat1.printName();
cat2.printName();

 

* this 바인딩

  • 자바, C#, C++ 대부분의 객체지향 프로그래밍 언어에서는 this는 항상 자신의 인스턴스 자체를 가리킴!
  • 정적으로 인스턴스가 만들어지는 시점에 this가 결정됨!
  • 하지만, 자바스크립트에서는 누가 호출하냐에 따라서 this가 달라짐!
  • 즉, this는 호출하는 사람(caller)에 의해 동적으로 결정됨!
// this 바인딩

function Cat(name) {
  this.name = name;
  this.printName = function () {
    console.log(`고양이의 이름을 출력한다옹: ${this.name}`);
  };
}

function Dog(name) {
  this.name = name;
  this.printName = function () {
    console.log(`강아지의 이름을 출력한다옹: ${this.name}`);
  };
}

const cat = new Cat('냐옹');
const dog = new Dog('멍멍');
cat.printName();
dog.printName();

// 동일한 this.name이여도 누가 객체를 호출하냐에 따라서 달라진다.
// object.함수()를 실행하면 해당 object가 this가 된다.
dog.printName = cat.printName;
dog.printName();
cat.printName();

// 함수를 callback으로 전달하면 this라는 정보를 잃어버려서 호출하는 사람이 누구냐에 따라서 this가 없어지거나 다른걸로 변경이 된다.
// 따라서 예상하지 못하는 문제가 생긴다.
// 해당 문제를 아래의 예시에서 확인해보자
function printOnMonitor(printName) {
  console.log('모니터를 준비하고!, 전달된 콜백을 실행!');
  printName();
}

// printName()함수의 호출하는 대상이 없기 때문에 undefined로 나오게 된다.
// 자바스크립트에서는 바인딩이 누가 호출하냐에 따라서 동적으로 변화된다.
printOnMonitor(cat.printName);

 

* 함수를 callback으로 전달하면 this라는 정보를 잃어버려서 호출하는 사람이 누구냐에 따라서 this가 없어지거나 다른걸로 변경이 된다.

=> arrow function을 사용하면 된다.

 

* arrow function

  • 정적으로 바인딩 해주려면 arrow function을 사용해주면 된다.
  • arrow 함수를 사용: arrow 함수는 렉시컬 환경에서의 this를 기억해요!
  • 화살표 함수 밖에서 제일 근접한 스코프의 this를 가리킴
  • 일반 함수는 동적으로 this가 결정이 되어서 누가 호출하냐에 따라서 this가 달라질 수 가 있지만 정적으로 결정되는 언어처럼 프로그래밍 하려면(this를 간직하고 기억하고 바인딩하고 싶다면) bind함수를 이용하던가 아니면 arrow function을 이용하면 된다.
function Cat(name) {
  this.name = name;
  
  // arrow function
  this.printName = () => {
    console.log(`고양이의 이름을 출력한다옹: ${this.name}`);
  };
  // bind 함수를 이용해서 수동적으로 바인딩 해주기
  // this.printName = this.printName.bind(this);
}

function Dog(name) {
  this.name = name;
  this.printName = function () {
    console.log(`강아지의 이름을 출력한다옹: ${this.name}`);
  };
}

const cat = new Cat('냐옹');
const dog = new Dog('멍멍');
cat.printName();
dog.printName();

dog.printName = cat.printName;
dog.printName();
cat.printName();

function printOnMonitor(printName) {
  console.log('모니터를 준비하고!, 전달된 콜백을 실행!');
  printName();
}

printOnMonitor(cat.printName);

'Study > JavaScript' 카테고리의 다른 글

[JavaScript_study] 바벨 (Babel)  (0) 2022.04.14
[JavaScript_study] arrow function (화살표 함수)  (0) 2022.04.14
[JavaScript_study] 클로저(Closure)  (0) 2022.04.14
[JavaScript_study] Mixin  (0) 2022.04.14
[JavaScript_study] 상속(inheritance) // prototype, class  (0) 2022.04.14
    'Study/JavaScript' 카테고리의 다른 글
    • [JavaScript_study] 바벨 (Babel)
    • [JavaScript_study] arrow function (화살표 함수)
    • [JavaScript_study] 클로저(Closure)
    • [JavaScript_study] Mixin
    갈푸라떼
    갈푸라떼

    티스토리툴바