Typeof to obtain a variable type, normally only returned the following results: the typeof number, Boolean, string, the function, object, undefined. We can use the typeof to obtain a variable exists, such as

if (typeof a!="undefined") {}, and not to use the if (a) because if there is no declaration of (not) a will make a mistake, for Array, and other special objects using typeof Null will be returned object, that is the limitation of the typeof.

if we want to obtain an object is an array, or to determine whether a variable is an object instance is to choose to use instanceof. Instanceof is used to determine whether a variable instance of an object, such as var a=new Array (); Alert (a instanceof Array); Returns true, alert at the same time (a instanceof Object) will return true; This is because the Array is a subclass of the object. Such as: the function test () {}; Var a=new test (); Alert (a instanceof test) will return true.

when it comes to instanceof we want to insert a question more, is the function of the arguments, we may consider the arguments is an Array, but if use instaceof to test will find the arguments is not an Array object, although look the same.

in the JavaScript is the instanceof operator returns a Boolean value, points out that the object is an instance of a particular class.
method of use:
the result=object instanceof class
the result of them will be options. Any variables.
object is option. Any object expression.
option class are a must. Arbitrarily defined object classes.

if the object is an instance of class, the instanceof operator returns true. If the object is not specified an instance of a class, or object is null, it returns false.

JavaScript in the instanceof operator
the following example illustrates the use of the instanceof operator.

function objTest (obj) {
var I, t, s="";//create a variable.
t=new Array ();//create an array.
t (" Date ")=Date;//fill the array.
t [" Object "]=Object;
t [" Array "]=Array;
the for (I in t)
{
if (obj instanceof [I] t)/check/obj class.
{
s +="obj is an instance of" + I + "\ n";

} else
{
s +="obj is not an instance of" + I + "\ n";

}}
the return (s);//return a string.
}

var obj=new Date ();
response. Write (objTest (obj));

you might be interested in the article:

  • about in javascript typeof and instanceof introduction
  • Array, the Array Constructor, the for loop, in typeof, instanceof
  • javascript instanceof, the difference between the typeof
  • javascript typeof, instanceof operator use to explore


This concludes the body part