JavaScript中instanceof运算符的用法总结

  JavaScript中instanceof运算符是返回一个 Boolean 值,指出对象是否是特定类的一个实例。

  使用方法:

  result = object instanceof class

  其中result是必选项。任意变量。

  object是必选项。任意对象表达式。

  class是必选项。任意已定义的对象类。

  说明

  如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。

  JavaScript中instanceof运算符

  下面的例子举例说明了 instanceof 运算符的用法。

  

复制代码 代码如下:

  function objTest(obj){

  var i, t, s = "";   // 创建变量。

  t = new Array();   // 创建一个数组。

  t["Date"] = Date;   // 填充数组。

  t["Object"] = Object;

  t["Array"] = Array;

  for (i in t)

  {

  if (obj instanceof t[i])   // 检查 obj 的类。

  {

  s += "obj is an instance of " + i + "/n";

  }

  else

  {

  s += "obj is not an instance of " + i + "/n";

  }

  }

  return(s);   // 返回字符串。

  }

  var obj = new Date();

  response.write(objTest(obj));