Getting the Name of an Object's Type in JavaScript
While Java offers the class.getName() method to retrieve the type of an object, JavaScript lacks a direct equivalent. However, several techniques can be employed to achieve a similar result.
One approach involves modifying the Object's prototype to add a getName() function:
Object.prototype.getName = function() { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec((this).constructor.toString()); return (results && results.length > 1) ? results[1] : """"; };
With this hack, all objects will now have a getName() method that returns the constructor's name as a string.
Another option is to use the constructor property. While it generally works for testing the type of an object like so:
var myArray = [1,2,3]; (myArray.constructor == Array); // true
However, there are certain caveats that can break its reliability, such as multiple inheritance or objects created without using the "new" keyword.
The instanceof operator is another alternative, but it also has its limitations. It fails to work for literal values and requires the object to be created using the correct constructor.
Another approach is to use the constructor.name property, although it may not be suitable for IE9 or below. For compatibility, a monkey-patch solution can be implemented:
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) { Object.defineProperty(Function.prototype, 'name', { get: function() { var funcNameRegex = /function\s([^(]{1,})\(/; var results = (funcNameRegex).exec((this).toString()); return (results && results.length > 1) ? results[1].trim() : """"; }, set: function(value) {} }); }
Finally, Object.prototype.toString can be used to determine the type for all built-in types, but it returns "Object" for all user-defined types.
It is important to be aware of the caveats and limitations of each approach when choosing a method to determine the type of an object in JavaScript.
The above is the detailed content of How Can I Get the Name of an Object's Type in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!