프로토타입 상속을 한 사용자 정의 객체를 사용할때는

typeof, instanceof, constructor 프로퍼티, toString() 메소드등의

도움을 얻어 판달할 필요가 있음.

var Parent = function(){};
Parent.prototype.constructorname = 'Parent';

var Child = function(){};
Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype.constructorname = 'Child';

var child = new Child();
document.writeln('typeof Parent : ' + typeof Parent + '
'); document.writeln('typeof Child : ' + typeof Child + '
'); document.writeln('typeof child : ' + typeof child + '
'); /* return: typeof Parent : function typeof Child : function typeof child : object * */ document.writeln('child instancdof Object : ' + ( child instanceof Object) + '
'); document.writeln('child instancdof Parent : ' + ( child instanceof Parent) + '
'); document.writeln('child instancdof Child : ' + ( child instanceof Child) + '
'); /* return: child instancdof Object : true child instancdof Parent : true child instancdof Child : true * */ document.writeln('child.constructor === Object: ' + ( child.constructor === Child) + '
'); document.writeln('child.constructor === Parent: ' + ( child.constructor === Parent) + '
'); document.writeln('child.constructor === Child: ' + ( child.constructor === Child) + '
'); /* return: child.constructor === Object: true child.constructor === Parent: false child.constructor === Child: true * */ function checkType(obj){ // null일 경우 문자열 'null' 반환 if(obj === null){ return 'null'; } //typeof가 'object'가 아닐경우 type반환 var type = typeof obj; if(type != 'object'){ return type; } //obj.toString()의 결과를 저장 var str = Object.prototype.toString.call(obj); // 생성자 이름 추출 var constructor = str.substring(8, str.length - 1); if(constructor != 'Object'){ return constructor; } if(obj.constructor == 'Object'){ return constructor; } // 사용자 정의 객체의 생성자 함수의 프로토타입 객체에 정의해 놓은 constructorname // 프로퍼티가 있으면 constructorname을 반환 if('constructorname' in obj.constructor.prototype) return obj.constructor.prototype.constructorname; return '객체의 타입을 알수 없습니다.'; } document.writeln('checkType(child) : ' + checkType(child) + '
'); /* return: checkType(child) : Child * */
Posted by 달팽이맛나
,