title

JavaScript에서 클래스를 사용할 때의 생성자

Tip&Tech | 2008.03.28 19:51

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);

이 같은 문제를 다음과 같은 두 가지 방법으로 해결할 수 있다.

  1. typeClass.prototype 을 재정의하지 않고 각각의 프로퍼티나 메소드를 덧붙인다.
  2. typeClass의 prototype.constructor 를 재정의한다.
      1  function typeClass() {
      2  }
      3  typeClass.prototype = {
      4    method : function() {
      5    }
      6  }
      7  typeClass.prototype.constructor = typeClass;
      8  var oInstance = new typeClass;
      9  alert(oInstance.constructor == typeClass);
     10  };

추가 // prototype.js에는 이런 문제가 수정되어있습니다. 제가 보던 때와는 달리 많이 변경된 것 같습니다. ^^;;