자바스크립트 에서의 this
javascript 2010.04.06 14:49 |현재 코드 상에서 this 는 대체 무얼까?
this 가 엉뚱한 걸 가르키거나 널이라는 에러를 많이 봤을 것이다.
<script type="text/javascript">
var mathObj = {
pi: 3.14,
getCircumference : function(data) {
alert(this.pi * 2 * data.radius);
}
}
</script>
위의 코드는 아무 문제가 없다.
컨텍스트가 변경되는 경우를 한번 살펴보자.
<script type="text/javascript">
var mathObj = {
pi: 3.14,
getCircumference : function(data) {
alert(this.pi * 2 * data.radius);
},
getRemoteCircumference: function(url) {
$.getJSON(url, this.getCircumference);
}
}
</script>
위의 코드에서는 ajax 의 콜백으로 getCircumference 를 호출한다.
즉 getJSON 함수가 내부에서 getCircumference 호출해 주는 것이다. 그렇다면 여기서 this 는 무엇을 가르킬까? 위의 코드는 this.pi 가 정의 되지 않았다는 에러가 나온다. 현재 컨텍스트는 외부 함수인 getJSON 이므로 여기서 this 키워드는 jquery 객체중 하나를 가르키게된다.
이것의 해결방법은
alert(mathObj.pi * 2 * data.radius); 이런식으로 this 를 쓰지않고 객체명을 직접 서술하는 방법인데,
this 를 쓸수 없다는 단점이 생긴다. this 를 쓸수 없으므로 함수 호출때 마다 객체명을 일일이 써줘야 한다.
좀 더 나은 방법은 apply 를 써서 scope 를 변경해 주는 것이다.
<script type="text/javascript">
function getContextFunc(context, func) {
return function() {
func.apply(context, arguments);
};
}
pi: 3.14,
getCircumference: function(data) {
alert(this.pi * 2 * data.radius);
},
getRemoteCircumference: function(url) {
$.getJSON(url, getContextFunc(this, this.getCircumference));
}
}
</script>
apply 첫번째 파라미터는 scope를 정의한다. scope 은 쉽게 말해 this 키워드가 어는 객체를 참조하게 할 것인지를 말한다.
getContextFunc(this, this.getCircumference) 이렇게 해서 getCircumference 가 실행될때 this 는 현재의 객체인 this를 가리키게 하여 pi 를 제대로 참조할 수 있게 하는 것이다.
'javascript' 카테고리의 다른 글
자바스크립트 에서의 this (0) | 2010.04.06 |
---|---|
동적 함수 호출 (2) | 2010.04.06 |
Cross Browser Cookie(브라우저에 상관없이 쿠키 공유하기) (0) | 2010.02.03 |
IE 와 firefox 쿠키 문제 (0) | 2010.02.03 |
Open Flash Chart (0) | 2009.12.08 |
The JSON Validator(JSon 스트링 유효성 검사) (0) | 2009.11.27 |
댓글을 달아 주세요