Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- jQuery
- GDI+
- 게으름
- silverlight
- 암호화
- 형태소분석기
- Web 2.0
- GTD
- XML
- Ajax
- 해킹
- C#
- 검색
- JavaScript
- 전기차
- 백신
- 성공
- COM+
- 구글
- WEb 2.0 Expo
- 실버라이트2
- ASP.NET
- .net
- 리팩토링
- Sliverlight
- 개발자
- hnd-7070
- 실버라이트
- MS
- 자바스크립트
Archives
- Today
- Total
꿈으로 가는 작은 계단
JavaScript에서 클래스를 사용할 때의 생성자 본문
http://mygony.com/archives/1403
JavaScript에서는 function 객체를 클래스 타입이자 생성자로 사용할 수 있다. 다음은 간단한 예제 코드이다.
function typeClass() { } var oInstance = new typeClass;
인스턴스를 생성할 때 사용한 클래스 겸 생성자인 typeClass는 인스턴스 객체의 constructor 속성으로 접근할 수 있다. 이는 Array, Object 등을 비롯한 JavaScript의 코어 객체도 마찬가지다.
function typeClass() {}; var oInstance = new typeClass; alert(oInstance.constructor == typeClass);
한편, 함수의 prototype 속성을 이용하면 상속도 가능하다. 유명한 프레임웍인 prototype.js 도 기본 원리는 다음의 코드와 비슷하게 구현이 되어있다.
function typeClass() {}; typeClass.prototype = { method : function(){} }; var oInstance = new typeClass;
이제 아까와 마찬가지로 constructor 속성에 접근해보도록 하자.
function typeClass() {}; typeClass.prototype = { method : function(){} }; var oInstance = new typeClass; alert(oInstance.constructor == typeClass);
어째 결과가 이상하지 않은가? typeof 연산자로 체크해봐도 oInstance.constructor 는 “function”이 아닌 “object” 타입으로 출력된다. 확실한 원인은 모르겠으나 prototype이 재정의되면서 이러한 문제가 발생하는 것 같다. 아래 코드에서는 여전히 constructor 가 function 으로 출력되고, typeClass는 oInstance의 클래스 타입이다.
function typeClass() {}; typeClass.prototype.method = function(){}; var oInstance = new typeClass; alert(oInstance.constructor == typeClass);
이 같은 문제를 다음과 같은 두 가지 방법으로 해결할 수 있다.
- typeClass.prototype 을 재정의하지 않고 각각의 프로퍼티나 메소드를 덧붙인다.
- typeClass의 생성자에서 다음과 같은 코드를 통해 constructor를 재정의한다.
1 function typeClass() { 2 this.constructor = typeClass; 3 } 4 typeClass.prototype = { 5 method : function() { 6 } 7 } 8 var oInstance = new typeClass; 9 alert(oInstance.constructor == typeClass); 10 };
'소프트웨어 > JavaScript • Dhtml' 카테고리의 다른 글
| 구글 AJAX Libraries API (0) | 2008.06.04 |
|---|---|
| XMLHttpRequest 번역본 2 (0) | 2008.04.22 |
| jsShortcut , JS 단축키 클래스 (0) | 2008.03.25 |
| appendChild와 innerHTML+=의 속도차이 (0) | 2008.03.25 |
| Javascript 의 표준 ECMA란? (0) | 2007.07.05 |