this 키워드

태로샐러드·2021년 7월 29일
0

javascript 기초

목록 보기
17/22
post-thumbnail

🍫 this란?

method는 '어떤 객체의 속성으로 정의된 함수'를 뜻한다.

const profile = {
   name : taero,
   hobby : LOL,
   comment : function () {
     return 'hi my name is' + profile.name
   }
}

위와 같이 profile이라는 객체가 하나 있다.
comment라는 key에는 문자열을 리턴하는 함수가 하나 담겨있다.
여기서 comment는 profile이라는 객체의 속성으로 정의된 함수인 'method'라고 볼 수 있다.
profile.comment()와 같은 형태로 사용(호출)이 가능하다.

전역변수에서 선언한 함수window 객체에 속한다.
다만 접두사 없이도 사용 가능하기 때문에 window.foo() 등으로 쓰지 않고
그냥 생략하여 foo() 라고 쓰는 것 뿐이다.

(사실 이거 보여 주려고 어그로 끌었다.)
method는 항상 '어떤 객체'의 method이다.
여기서 말하는 '어떤 객체' 가 지칭하는 것이 바로 this 이다.

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

a(); // window {}

전역 변수에서 선언된 함수의 this는 위에서 말했듯 window 객체 다.

const profile = {
   name : taero,
   hobby : LOL,
   comment : function () {
     return 'hi i am ' + this.name;   // 'hi i am taero'
   }
}

comment 함수에서 쓰인 this는 profile 객체를 지칭한다.
정확히는 해당 객체의 method를 호출할 때, 내부적으로 this를 바꿔주는 것이다.

하지만 저 함수를 새로운 변수에 담는다면?

const a = profile.comment;

이렇게 되면 a의 this는 다시 window가 된다.
profile.comment를 꺼내서 전역함수로 선언한 것이기 때문이다.

이런 상황에 원래 객체의 this참조를 유지하고 싶다면,
bind, call, apply 메소드를 사용하면 된다.

🍫 bind

const module = {
  x : 42,
  getX : function() {
    return this.x;
  }
}

const a = module.getX;
console.log(a()); // undefined

module.getX를 새로운 변수에 집어넣고 콘솔을 찍었더니,
this가 window로 바뀌어 this.x 는 undefined가 된다.

const b = module.getX.bind(module);
console.log(b());  // 42

이럴 때 bind method를 사용하면,
b는 module 객체에 bind(묶여)되어 원하는 값을 출력할 수 있다.

bind는 바로 호출은 되지 않아서 저렇게 변수에 담아서 사용해야 한다.

🍫 call, apply

  • bind와 다르게 이 둘은 바로 호출도 가능하다.
  • func.call (thisArg, a, b, c ...) 의 형태로 사용한다.
  • 첫번째 인자인 thisArg는 함수(method)를 소유하는 객체를 지정하고 그 뒤의 인자들은 필요에 따라서 함수로 보내는 인자들을 설정할 수 있다.
  • apply 도 call과 동일하지만, 유일한 차이점은 첫번째 인자 뒤 옵션인 인자들을 배열의 형태로 넣어야 한다는 점이다.
  • func.apply (thisArg, [a,b,c ...] ) 의 형태다.
var koGreeting = { 
  greeting : "안녕", 
  name : "홍길동", 
  sayHello: function() { 
  return this.greeting + ", " + this.name; 
  } 
}; 

var enGreeting = { greeting: "Hello", name: "HongKilDong" }; 

console.log(koGreeting.sayHello.call(enGreeting)); 
결과)
Hello, Hong KilDong

출처: https://offbyone.tistory.com/140 [쉬고 싶은 개발자]

koGreeting.sayHello method를 이용하는데,
enGreeting 객체를 call 해와서 해당 method의 리턴값에 있는 this는
enGreeting 객체를 지칭하게 된다.
따라서 위와 같은 결과를 보여준다.

profile
기획, 개발공부, 그 외 잡다한 여정 기록 (SEMI로)

0개의 댓글