|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 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 * Date: 14 Mar 2001 |
|
8 * |
|
9 * SUMMARY: Utility functions for testing objects - |
|
10 * |
|
11 * Suppose obj is an instance of a native type, e.g. Number. |
|
12 * Then obj.toString() invokes Number.prototype.toString(). |
|
13 * We would also like to access Object.prototype.toString(). |
|
14 * |
|
15 * The difference is this: suppose obj = new Number(7). |
|
16 * Invoking Number.prototype.toString() on this just returns 7. |
|
17 * Object.prototype.toString() on this returns '[object Number]'. |
|
18 * |
|
19 * The getJSType() function below will return '[object Number]' for us. |
|
20 * The getJSClass() function returns 'Number', the [[Class]] property of obj. |
|
21 * See ECMA-262 Edition 3, 13-Oct-1999, Section 8.6.2 |
|
22 */ |
|
23 //----------------------------------------------------------------------------- |
|
24 |
|
25 |
|
26 var cnNoObject = 'Unexpected Error!!! Parameter to this function must be an object'; |
|
27 var cnNoClass = 'Unexpected Error!!! Cannot find Class property'; |
|
28 var cnObjectToString = Object.prototype.toString; |
|
29 var GLOBAL = 'global'; |
|
30 |
|
31 // checks that it's safe to call findType() |
|
32 function getJSType(obj) |
|
33 { |
|
34 if (isObject(obj)) |
|
35 return findType(obj); |
|
36 return cnNoObject; |
|
37 } |
|
38 |
|
39 |
|
40 // checks that it's safe to call findType() |
|
41 function getJSClass(obj) |
|
42 { |
|
43 if (isObject(obj)) |
|
44 return findClass(findType(obj)); |
|
45 return cnNoObject; |
|
46 } |
|
47 |
|
48 |
|
49 function findType(obj) |
|
50 { |
|
51 return cnObjectToString.apply(obj); |
|
52 } |
|
53 |
|
54 |
|
55 // given '[object Number]', return 'Number' |
|
56 function findClass(sType) |
|
57 { |
|
58 var re = /^\[.*\s+(\w+)\s*\]$/; |
|
59 var a = sType.match(re); |
|
60 |
|
61 if (a && a[1]) |
|
62 return a[1]; |
|
63 return cnNoClass; |
|
64 } |
|
65 |
|
66 |
|
67 function isObject(obj) |
|
68 { |
|
69 return obj instanceof Object; |
|
70 } |
|
71 |