오늘도 개발

자바스크립트의 this 본문

웹 프로그래밍/Javascript

자바스크립트의 this

Sueeeeeee 2022. 10. 17. 17:15

1. 메서드(Method)란?

객체에 정의한 함수.

 

2. this

this는 this가 바라보고 있는 객체.

 

일반 함수인 경우(function 함수)

this는 호출 시(=실행 컨텍스트 생성 시) 결정된다.

node.js인 경우 this는 global 객체.

브라우저에서 실행하는 경우 this는 window 객체. 

function test() {
  console.log(this);
}
test(); // global object

 

method인 경우

this는 호출 시(=실행 컨텍스트 생성 시) 결정된다.

this는 메서드가 정의된 객체.

const snoopy = {
  name: 'snoopy',
  greet: function () {
    console.log(this); // snoopy object
    console.log(this.name); // snoopy
  },
};

snoopy.greet();
const name = 'garfield';

const snoopy = {
  name: 'snoopy',
  sayThis: function () {
    console.log(this); // snoopy 오브젝트
  },
  outer: function () {
    function inner() {
      console.log(this); // global 오브젝트
    }
    inner();
  },
};

snoopy.sayThis();
snoopy.outer();

 

애로우 함수인 경우

this는 함수를 정의한 위치에 따라 결정된다. 즉, 선언 시 결정된다.

함수 자체 this를 갖지 않음. scope chain에서 가장 가까운 부모의 this를 자신의 this로 가짐.

const name = 'garfield';

const snoopy = {
  name: 'snoopy',
  sayThis: () => console.log(this) // global object
};

snoopy.sayThis();

 

3. 암시적 바인딩 VS 명시적 바인딩

암시적 바인딩

메서드를 정의한 객체가 자동으로 메서드의 this가 되는 것.

 

명시적 바인딩

원하는 대상을 this로 설정하는 것.

한 오브젝트의 메서드를 다른 곳에서도 쓸 수 있게 해준다.

 

1) call : call 호출 시 this로 삼을 객체를 인자로 넣음

const snoopy = {
  name: 'Snoopy',
  woodstock: {
    name: 'Woodstock',
    getName: function () {
      console.log(this.name);
    },
  },
};

snoopy.woodstock.getName(); // Woodstock
snoopy.woodstock.getName.call(snoopy); // Snoopy

 

2) apply : call과 동일한데 인수로 배열을 넣을 수 있음

const number1 = {
  num: 1,
};

const number2 = {
  num: 2,
};

function add(a, b) {
  console.log(this.num + a + b);
}

add.apply(number1, [1, 2]); // 4
add.apply(number2, [1, 2]); // 5

 

3) bind : call과 비슷한데 call과 달리 즉시 함수를 호출하지 않고 바인딩만 함

const number = {
  num: 1,
};

function add(a, b) {
  console.log(this.num + a + b);
}

const addNumbers = add.bind(number, 1, 2);
addNumbers(); // 4

'웹 프로그래밍 > Javascript' 카테고리의 다른 글

리액트 개요  (0) 2023.12.19
비교 연산자 ==와 ===  (0) 2023.12.05
jest로 unit test하기  (0) 2022.10.02
Layered Pattern  (0) 2022.10.01
Node.js에서 인증, 인가 진행하기(bcrypt, jwt)  (0) 2022.09.29