프로토타입 상속을 한 사용자 정의 객체를 사용할때는
typeof, instanceof, constructor 프로퍼티, toString() 메소드등의
도움을 얻어 판달할 필요가 있음.
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | 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 * */ |