JS is a loose type of language, this point JS object is particularly prominent. So how to determine the specific type of JS object?
First, we can use the TypeOf operator to determine its base type (number,object,function,undefined). If the typeof operator returns object, we then use instanceof to determine whether the object belongs to a specific type.
Note: typeof null gets the object, while TypeOf undefined gets the undefined,typeof array object gets the object,typeof function to get functions.
o instanceof Type: Determines whether the object o belongs to type, and if O is an instance of the type subclass, it is also satisfied. Like what
var o=instanceof Array); // true instanceof Object); // true var f=functioninstanceof function); // true instanceof Object); // true
If you want to determine whether an object is an instance of a specific class (subclass), you can look at the constructor property of that object.
var d=new Date (); alert (d instanceof Object); Span style= "color: #008000;" >// true alert (d.constructor==object); // false alert (d.constructor==date); // true
The disadvantage of the
using instanceof and constructor for type judgments is that you can only test objects based on the classes you already know, but not the objects in the location. An interesting phenomenon of the default ToString () method defined by object is that it reveals information about object types. The ECMAScript specification requires this default ToString () method to always return a string of the following form:
[Object class]
class is the internal type of the object, usually corresponding to the name of the constructor of the object. For example, the class of an array object is an array, the class of the function is the class of the Function,date object, and the class of the Date,math object is math. For user-defined types, class is object, and the client's JS object class may be window, Document, form, etc.
But most classes override the default ToString method, You need to call the default function as shown in Object.prototype, and call it on an object of interest to apply ():
Object.prototype.toString.apply (o);
var d=New Date (); Alert (Object.prototype.toString.apply (d)); // [Object Date] var a=[];alert (Object.prototype.toString.apply (a)); // [Object Array]
Tool methods for getting the object type
functionGetType (x) {if(x==NULL){ return"NULL"; } vart=typeofx; if(t!= "Object"){ returnT; } varC=Object.prototype.toString.apply (x); C=c.substring (8,c.length-1); if(c!= "Object"){ returnC; } if(x.constructor==Object) { returnC}if("ClassName"inchX.prototype.constructor&&typeofx.prototype.constructor.classname== "string"){ returnX.constructor.prototype.classname; } return"<unknown type>";}