call과 bind를 이해하려면 javascript의 this 스코프를 알아야 한다.


var q = document.querySelector 를 이렇게 짧게 쓰려고 한다면?

q("form")을 실행하는 순간 Uncaught TypeError : Illegal invocation at 라고 에러가 발생한다. 

왜 그럴까?
인자가 어떻게 전달되는지 알아야 한다.
"form"라는 인자는 querySelector에 this.form 비슷하게 전달된다.
docuement.querySelector("form")이라고 한다면
this 는 document를 가르키지만
q로 빠지는 순간 this는 window가 된다.
그래서 엉뚱한 "form"을 찾으려하니 에러가 발생한다.

이를 해결하기 위해서 this를 지정해 주는 함수가 call과 bind이다.
위의 문제를 해결하려고 하면
document.querySelector.bind(document) 라고 해주면
this가 window가 아니라 document가 되므로 정상적으로 q를 사용할 수 있다.

bind를 객체에 this를 주입하는 것이고
call은 this를 주입해서 함수를 실행 시킬 수 있다.
  var a = {
x : 1
  };
var obj = {
test : function(){console.log(this.x)}
};
  obj.test();
obj.test.call(a); 

결과 :

 undefined

 1

'javascript' 카테고리의 다른 글

ie, chrom] new Date 관련  (0) 2017.12.27
jquery outerHTML  (0) 2017.12.27
IE에서 inline style 자동 파싱 문제  (0) 2017.12.27
Closure의 중요성  (0) 2017.07.08
&& 와 || 는 if 문에서만 쓰이는 것이 아니다.  (0) 2017.06.18

+ Recent posts