JavaScript get_class
Retrieves the class name
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 | function get_class (obj) { // Retrieves the class name // // version: 909.322 // discuss at: http://phpjs.org/functions/get_class // + original by: Ates Goral (http://magnetiq.com) // + improved by: David James // * example 1: get_class(new (function MyClass() {})); // * returns 1: "MyClass" // * example 2: get_class({}); // * returns 2: "Object" // * example 3: get_class([]); // * returns 3: false // * example 4: get_class(42); // * returns 4: false // * example 5: get_class(window); // * returns 5: false // * example 6: get_class(function MyFunction() {}); // * returns 6: false if (obj instanceof Object && !(obj instanceof Array) && !(obj instanceof Function) && obj.constructor && obj != this.window) { var arr = obj.constructor.toString().match(/function\s*(\w+)/); if (arr && arr.length == 2) { return arr[1]; } } return false;} |
Examples
» Example 1
Running
1 | get_class(new (function MyClass() {})); |
Should return
1 | "MyClass" |
» Example 2
Running
1 | get_class({}); |
Should return
1 | "Object" |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have get_class goodness in JavaScript.

for get_class() I suggest adding the i flag to the regex to accomodate Function as well as function
Kevin van Zonneveld
16 Feb '08