JS Object.toString()测试对象的类型

文章作者:中山市飞娥软件工作室「Feiesoft.com」  浏览次数:3132 次  更新日期:2013-10-29

<pre><script type="text/javascript">
//JS Object.toString()测试对象的类型
//JS o instanceof C 运算符与o.constructor属性只能根据已知的类进行测试对象,对于未知的对象,可以通过下面的方法检测其准确的类型:
 function getType(x){
  
  if(x == null)return "null";
  
  var t = typeof x;
  if(t != "object")return t;
  
  var c = Object.prototype.toString.apply(x);
  c = c.substring(8,c.length - 1);
  if(c != "Object")return c;
  
  if(x.constructor == Object)return c;
  
  if("classname" in x.constructor.prototype && typeof x.constructor.prototype.classname == "string")return x.constructor.prototype.classname;
  
  return "[unknown type]";
 
 }
 var num = 2014.1;
 var str = "feiesoft.com";
 var boo = false;
 var arr = new Array();
 var fun = function(){};
 var obj = {};
 var now = new Date();
 var win = this;

 document.writeln("getType(num) = " + getType(num));// getType(num) = number
 document.writeln("getType(str) = " + getType(str));// getType(str) = string
 document.writeln("getType(boo) = " + getType(boo));// getType(boo) = boolean
 document.writeln("getType(arr) = " + getType(arr));// getType(arr) = Array
 document.writeln("getType(fun) = " + getType(fun));// getType(fun) = function
 document.writeln("getType(obj) = " + getType(obj));// getType(obj) = Object
 document.writeln("getType(now) = " + getType(now));// getType(now) = Date
 document.writeln("getType(win) = " + getType(win));// getType(win) = Window

</script></pre>