shell.js (1726B)
1 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ 2 /* This Source Code Form is subject to the terms of the Mozilla Public 3 * License, v. 2.0. If a copy of the MPL was not distributed with this 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 5 6 /*--- 7 defines: [getJSClass, findType, findClass, isObject] 8 allow_unused: True 9 ---*/ 10 11 /* 12 * Date: 14 Mar 2001 13 * 14 * SUMMARY: Utility functions for testing objects - 15 * 16 * Suppose obj is an instance of a native type, e.g. Number. 17 * Then obj.toString() invokes Number.prototype.toString(). 18 * We would also like to access Object.prototype.toString(). 19 * 20 * The difference is this: suppose obj = new Number(7). 21 * Invoking Number.prototype.toString() on this just returns 7. 22 * Object.prototype.toString() on this returns '[object Number]'. 23 * 24 * The getJSClass() function returns 'Number', the [[Class]] property of obj. 25 * See ECMA-262 Edition 3, 13-Oct-1999, Section 8.6.2 26 */ 27 //----------------------------------------------------------------------------- 28 29 30 var cnNoObject = 'Unexpected Error!!! Parameter to this function must be an object'; 31 var cnNoClass = 'Unexpected Error!!! Cannot find Class property'; 32 var cnObjectToString = Object.prototype.toString; 33 var GLOBAL = 'global'; 34 35 36 // checks that it's safe to call findType() 37 function getJSClass(obj) 38 { 39 if (isObject(obj)) 40 return findClass(findType(obj)); 41 return cnNoObject; 42 } 43 44 45 function findType(obj) 46 { 47 return cnObjectToString.apply(obj); 48 } 49 50 51 // given '[object Number]', return 'Number' 52 function findClass(sType) 53 { 54 var re = /^\[.*\s+(\w+)\s*\]$/; 55 var a = sType.match(re); 56 57 if (a && a[1]) 58 return a[1]; 59 return cnNoClass; 60 } 61 62 63 function isObject(obj) 64 { 65 return obj instanceof Object; 66 }