넥사크로 객체의 종류 알아내기 — typeof 대신 instanceof
공통 함수에 넘어온 인자가 Dataset 인지 Grid 인지 가려야 할 때가 있다. 결론부터: instanceof 를 쓴다.
this.ds_list instanceof nexacro.Dataset; // true
this.ds_list instanceof Dataset; // true (전역 이름으로도 된다)
this.grd_list instanceof nexacro.Grid; // true
typeof 는 모두 ‘object’
typeof this.ds_list; // 'object'
typeof this.div_search; // 'object'
typeof this.grd_list; // 'object'
넥사크로라서 그런 것이 아니라 자바스크립트 규칙이다. typeof 는 원시 타입(string, number, boolean, undefined, symbol, bigint)과 함수(function)만 구분하고, 그 밖의 객체는 클래스와 상관없이 모두 'object' 를 돌려준다(null 도 'object'). 그래서 typeof 로는 Dataset 과 Grid 를 가를 수 없다.
toString() 은 이름을 보여 준다
this.ds_list.toString(); // '[object Dataset]'
this.div_search.toString(); // '[object Div]'
this.grd_list.toString(); // '[object Grid]'
넥사크로 라이브러리(Framework.js)를 보면 공통 부모의 toString 이 내부 속성 _type_name 을 끼워 넣도록 되어 있다.
_pObject.toString = function () {
return "[object " + this._type_name + "]";
};
콘솔에서 눈으로 확인할 때는 편하다. 다만 _type_name 은 _ 로 시작하는 내부 속성이라 공식 API 가 아니고, 문자열 비교는 오타에도 약하다. 코드에서 분기할 때는 쓰지 않는다.
instanceof 로 구분한다
instanceof 는 객체의 prototype 사슬에 그 클래스의 prototype 이 있는지 본다. 넥사크로 클래스는 nexacro.Dataset, nexacro.Grid 처럼 nexacro 아래에 있고, Dataset 같은 전역 이름으로도 접근할 수 있다(제가 쓴 버전에서 둘 다 true 였다).
this.fn_getKind = function (obj) {
if (obj instanceof nexacro.Dataset) return "Dataset";
if (obj instanceof nexacro.Grid) return "Grid";
if (obj instanceof nexacro.Div) return "Div";
return "etc";
};
상속 관계도 따라가므로, 부모 클래스로 검사하면 자식 클래스 객체도 true 가 된다. 정확히 한 종류만 고르고 싶으면 자식 클래스부터 검사한다.
다시 쓰며 바로잡은 점
- 원문은 “넥사크로 객체는 typeof 가 모두 object” 라고만 했는데, 이는 넥사크로가 아니라 자바스크립트
typeof의 규칙이라는 점을 밝혔다 _type_name은 내부 속성이므로 코드 분기에는instanceof를 쓰라고 정리했다- 그림으로 된 콘솔 결과를 글자로 옮기고, 데이터셋·그리드 이름을 일반적인 예시로 바꿨다