this

ALTANIS·2021년 2월 25일
0

this ?

  • 함수 실행시 호출 방법에 의해 결정되는 특별한 객체이다.
  • 함수 실행시 결정되기 때문에 코드 내용에 따라 this는 다르게 결정된다.

어떻게 실행 되나요?

  • 함수를 호출할 때 (거의 쓸일이 없다)
  • Method를 호출할 때
  • new 키워드를 이용해 생성자를 호출할 때
  • call, apply를 호출할 때

이처럼 각각 실행에 따라서 this는 다르게 결정된다.

Method를 호출할 때 this의 값

  • 실행 시점에 온점 왼쪽에 있는 객체

new 키워드를 이용해 생성자를 호출할 때

  • 새롭게 생성된 인스턴스 객체

call, apply를 호출할 때

  • 첫번째 인자로 전달된 객체

👀 this 주의사항

화살표 함수에서 this는 사용하지 말자.
화살표 함수는 this를 결정하지 않는다!
this를 사용하고 싶다면 일반함수를 이용하자




.call .apply .bind ?

  • 함수 호출 방식과 관계없이 this를 지정할 수 있다.

call 메소드

  • 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있다.
  • 첫번째 인자는 무조건 this 값이다.
  • 두번째 인자부터 일반 함수처럼 파라미터를 직접 받는다.

apply 메소드

  • 함수 매개변수를 처리하는 방법을 제외하면 call과 일치한다.
  • 첫번째 인자는 무조건 this 값이다.
  • 두번째 인자부터 파라미터를 배열로 받는다.

call과 apply 예제

const nike = {
  name : "Nike"
}

const adidas = {
  name : "Adidas"
}

function showBrand(){
 console.log(this.name); 
}

function update(price,category){
  this.price = price;
  this.category = category;
  
  update.call(nike, 20000, "Shoes"); // call은 2번째 인자부터 직접 받는다.
  console.log(nike); // {name : "Nike", price : 20000, category : "Shoes"}
  
  update.apply(adidas,[30000, "T-shirt"]); // apply는 2번째 인자부터 배열로 받는다.
  console.log(adidas); // {name : "Adidas", price : 30000, category : "T-shirt"}

bind 메소드

  • 함수의 값을 영구적으로 바꿀 수 있다.
  • 위 메소드 처럼 첫번째 인자는 무조건 this 값이다.
  • 당장 실행하지는 않고 this를 바인딩 된 함수를 리턴한다.
const nike = {
  name : "Nike"
}

const adidas = {
  name : "Adidas"
}

function showBrand(){
 console.log(this.name); 
}

function update(price,category){
  this.price = price;
  this.category = category;
  
updateNike = update.bind(nike); // 이 함수는 항상 nike를 this로 받는다.
updateNike(40000, 'Shoes'); // {name : "Nike", price : 40000, category : "Shoes"}

0개의 댓글