Get the Name of an Object's Type
In JavaScript, there is no direct equivalent to Java's class.getName() method for retrieving the name of an object's type. However, various approaches can be used for this purpose.
Using the Constructor Property
The constructor property of an object references its constructor function. For most objects, the constructor property will point to the constructor function used to create the object.
var myArray = [1, 2, 3]; myArray.constructor == Array; // true
However, this method has limitations:
Using the Instanceof Operator
The instanceof operator checks whether an object is an instance of a particular constructor function.
myArray instanceof Array; // true myArray instanceof Object; // true
This method also has limitations:
Using the Name Property of the Constructor Property
Starting with IE9, the constructor.name property of an object can be used to retrieve the name of the constructor function.
myArray.constructor.name; // "Array"
However, this method is not reliable in earlier versions of Internet Explorer.
Using Object.prototype.toString
The Object.prototype.toString method returns a string representation of the object's type.
Object.prototype.toString.call('abc'); // "[object String]" Object.prototype.toString.call(/abc/); // "[object RegExp]" Object.prototype.toString.call([1, 2, 3]); // "[object Array]"
This method can be used to get the type name for all built-in types. However, it will return "Object" for all user-defined types.
Caution
It's important to note that the type of an object may change depending on how it is constructed. For example, if a function is defined anonymously, its constructor property will be assigned to Anonymous.
The above is the detailed content of How Can I Get the Type Name of a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!