this 바인딩

gak·2023년 1월 3일
0

this 바인딩

this 바인딩은, 현재 함수가 실행되는 context 에 this 가 매핑되는 것이다.

예를들어 아래의 경우가 있다.

function foo() {
  this.a = 10;
};

foo();
console.log(this.a); // undefined

foo() 함수 내부에서 this 가 존재하고, this.a 가 10으로 만들어졌지만,
전역에서 this 는 foo() 함수 내부에서 존재하던 this 와는 다르기 때문에 this.a 는 undefined 이다.


그럼 어떻게?

특정 함수 내부의 this 를 우리가 원하는 this 로 만들기 위한 몇가지 테크닉이 있다.

1.ES6 화살표 함수

const foo = () => {
	this.a = 10;
};

foo();
console.log(this.a); // 10

위 예시처럼, 화살표 함수는 함수 내부의 this 를 따로 갖지 않아서, 외부 context 의 this 를 사용하게 된다. 위 예시에서는 전역 this 를 사용.

2. this binding

function foo() {
  this.a = 10;
};

const boo = foo.bind(this);

boo();
console.log(this.a); // 10

foo 함수에 전역 this 를 바인딩해서 foo 함수 내부 this 가 전역의 this 를 가리키게 만든다.

3. this 를 변수에 저장하기

const _this = this;

function foo() {
  _this.a = 10;
};

foo();
console.log(this.a); // 10

간단하게 전역 변수 _this, that, self같은 애들에 원하는 this 를 바인딩해준다.
그리고 함수 내부에서 this 를 사용하는게 아니라, 전역 변수를 사용한다.

profile
Hello. I'm Front-End Developer Trying to Create Valuable Things.

0개의 댓글