| 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 | gTestsubsuite = 'Object'; |
| 26 | |
| 27 | var cnNoObject = 'Unexpected Error!!! Parameter to this function must be an object'; |
| 28 | var cnNoClass = 'Unexpected Error!!! Cannot find Class property'; |
| 29 | var cnObjectToString = Object.prototype.toString; |
| 30 | var GLOBAL = 'global'; |
| 31 | |
| 32 | // checks that it's safe to call findType() |
| 33 | function getJSType(obj) |
| 34 | { |
| 35 | if (isObject(obj)) |
| 36 | return findType(obj); |
| 37 | return cnNoObject; |
| 38 | } |
| 39 | |
| 40 | |
| 41 | // checks that it's safe to call findType() |
| 42 | function getJSClass(obj) |
| 43 | { |
| 44 | if (isObject(obj)) |
| 45 | return findClass(findType(obj)); |
| 46 | return cnNoObject; |
| 47 | } |
| 48 | |
| 49 | |
| 50 | function findType(obj) |
| 51 | { |
| 52 | return cnObjectToString.apply(obj); |
| 53 | } |
| 54 | |
| 55 | |
| 56 | // given '[object Number]', return 'Number' |
| 57 | function findClass(sType) |
| 58 | { |
| 59 | var re = /^\[.*\s+(\w+)\s*\]$/; |
| 60 | var a = sType.match(re); |
| 61 | |
| 62 | if (a && a[1]) |
| 63 | return a[1]; |
| 64 | return cnNoClass; |
| 65 | } |
| 66 | |
| 67 | |
| 68 | function isObject(obj) |
| 69 | { |
| 70 | return obj instanceof Object; |
| 71 | } |
| 72 |