1/* 2* The contents of this file are subject to the Netscape Public 3* License Version 1.1 (the "License"); you may not use this file 4* except in compliance with the License. You may obtain a copy of 5* the License at http://www.mozilla.org/NPL/ 6* 7* Software distributed under the License is distributed on an "AS 8* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or 9* implied. See the License for the specific language governing 10* rights and limitations under the License. 11* 12* The Original Code is mozilla.org code. 13* 14* The Initial Developer of the Original Code is Netscape 15* Communications Corporation. Portions created by Netscape are 16* Copyright (C) 1998 Netscape Communications Corporation. All 17* Rights Reserved. 18* 19* Contributor(s): pschwartau@netscape.com 20* Date: 14 Mar 2001 21* 22* SUMMARY: Utility functions for testing objects - 23* 24* Suppose obj is an instance of a native type, e.g. Number. 25* Then obj.toString() invokes Number.prototype.toString(). 26* We would also like to access Object.prototype.toString(). 27* 28* The difference is this: suppose obj = new Number(7). 29* Invoking Number.prototype.toString() on this just returns 7. 30* Object.prototype.toString() on this returns '[object Number]'. 31* 32* The getJSType() function below will return '[object Number]' for us. 33* The getJSClass() function returns 'Number', the [[Class]] property of obj. 34* See ECMA-262 Edition 3, 13-Oct-1999, Section 8.6.2 35*/ 36//------------------------------------------------------------------------------------------------- 37var cnNoObject = 'Unexpected Error!!! Parameter to this function must be an object'; 38var cnNoClass = 'Unexpected Error!!! Cannot find Class property'; 39var cnObjectToString = Object.prototype.toString; 40 41 42// checks that it's safe to call findType() 43function getJSType(obj) 44{ 45 if (isObject(obj)) 46 return findType(obj); 47 return cnNoObject; 48} 49 50 51// checks that it's safe to call findType() 52function getJSClass(obj) 53{ 54 if (isObject(obj)) 55 return findClass(findType(obj)); 56 return cnNoObject; 57} 58 59 60function findType(obj) 61{ 62 return cnObjectToString.apply(obj); 63} 64 65 66// given '[object Number]', return 'Number' 67function findClass(sType) 68{ 69 var re = /^\[.*\s+(\w+)\s*\]$/; 70 var a = sType.match(re); 71 72 if (a && a[1]) 73 return a[1]; 74 return cnNoClass; 75} 76 77 78function isObject(obj) 79{ 80 return obj instanceof Object; 81} 82